Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

In general, it is a bad idea to mix multiple increment operations like this in a single expression in C and C++ because it usually results in undefined behavior. With undefined behavior, having things mysteriously change behavior isn't unsurprising.

Java on the other hand provides a rigid specification for all arithmetic and logical operations (with the exception of floating point exponent precision in non fpstrict expressions). You could put all these into Java (ignoring the fact that ints are no longer valid boolean expressions) and have them give you a consistent answer, though it may not be what you expect.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top