Search code examples
c++floating-point-exceptions

Mysterious Floating Point Exception


Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

My friend and I were messing round trying to come up with the worst for loops we could think of (so don't tell me this is terrible code, because it's supposed to be!).

My friend came up with this for loop:

for (int i = 0; i++ & ++i % (++i % 2) ? --i : i++; i++);

It looks ok but it fails to enter even for the first time due to a floating point exception. So my first thought was that the modulo divides by 0. But it doesn't seem to, because if you do this, it runs fine:

for (int i = 0; i < 100; i++) {
    i++ & ++i % (++i % 2);
}

but this will not:

for (int i = 0; i < 100; i++) {
    i++ & ++i % (++i % 2) ? --i : i++;
}

But it gets stranger. The first case runs fine the second case will not:

for (int i = 0; i < 100; i++) {
    i++ & ++i % (++i % 2) ? 0 : 1;
}

for (int i = 0; i < 100; i++) {
    i++ & ++i % (++i % 2) ? 1 : 0; // 1 and 0 switched
}

So by now I really confused at what is going on, but it gets weirder again. If you put the case with ? 0 : 1 (which ran fine) into an if statement it throws the floating point exception again:

for (int i = 0; i < 100; i++) {
    if (i++ & ++i % (++i % 2) ? 0 : 1);
}

I'm totally lost at this. Anyone got any ideas what's happening here?


Solution

  • It goes wrong at i++ & ++i. The & operator does not sequence its operands so putting an increment on both sides results in undefined behavior.

    By the way, it's probably a divide by zero exception, but not necessarily from the FPU.