原文恕刪
用setjmp/longjmp來模擬while loop
這裡有測試結果
http://ideone.com/PetGBe
以下是程式碼
#include <stdio.h>
#include <setjmp.h>
int abs(int value) {
jmp_buf buf;
char buffer[16];
snprintf(buffer, sizeof(buffer), "%d+", value);
char *cursor = buffer;
switch (setjmp(buf)) {
case 0:
++cursor;
longjmp(buf, *cursor);
case '-':
*cursor = ' ';
++cursor;
longjmp(buf, *cursor);
case '+':
*cursor = '\0';
sscanf(buffer, "%d", &value);
return value;
default:
++cursor;
longjmp(buf, *cursor);
}
}
int main(void) {
int value;
while (1 == scanf("%d", &value)) {
printf("%d\n", abs(value));
}
return 0;
}