For some reason when I return from the signal handler for SIGFPE, the variable i is one less than I expect it to be, to get the correct results from my program (iterate through all of the pairs in the pairs array) I must check the return value of sigsetjmp and increment i if I am returning from a signal "catch". Why is this? Why is the incrementation that happens during the iteration of the floating point exception lost?
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <setjmp.h>
jmp_buf e;
int i;
void float_exception ();
int main ()
{
int pairs[][2] = {
{10, -5}, {10, -3}, {-10, -3}, {-10, -5}, {-10, 3}, {-10, 5}, {-10, 0},
{10, 0}, {0, 10}, {2, 3}, {3, 3}, {5, 10}
};
int npairs;
/* handle sigfpe so /0 doesn't interrupt the rest of the program */
signal (SIGFPE, float_exception);
printf ("Seeing what my C implementation does with negative or 0 modulo"
"\narithmetic.\n");
npairs = sizeof (pairs) / sizeof (int) / 2;
i = 0;
if (sigsetjmp (e, 1) != 0) {
i++; /* without this line, i is one less than I expect it to be */
}
for (; i < npairs - 1; i++) {
printf ("%d: %d %% %d\t= ", i, pairs[i][0], pairs[i][1]);
fflush (stdout);
printf ("%d\n", pairs[i][0] %pairs[i][1]);
fflush (stdout);
}
return 0;
}
void float_exception ()
{
printf ("fpe\n");
fflush (stdout);
longjmp (e, 1);
}