Skip to main content

Poll results: How many iterations there will be in "for (int i = 0; i < 2^4; ++i) {}"

Posted in

Remember this poll? The final results are as following:

and it is time to reveal the magic. There are two tricks with this loop. Well, they are not real tricks, but you have to be very attentive to what language you are writing in.

for (int i = 0; i < 2^4; ++i)
    // ...

So, the first "trick" is that 2^4 is not the same as 2 to the power of 4. 2^4 is 2 XOR 4 and equals to 6.

The second "trick" is that the operator priority is not as it seems to us, i.e. XOR is done after the comparison with < operator.

i=0 => (i < 2) is true => XOR 4 is ... let it be N
i=1 => (i < 2) is true => XOR 4 is ... let it be N too.
i=2 => (i < 2) is false => 0 XOR 4 is 4
and so on.

some value XOR 4 is very often greater than 0. I know that "very often" sounds inaccurate. The only value that makes it equal to 4 is 4, i.e. 4 XOR 4 is 4.
It means, that in theory the number of iterations is undefined, but in practice I always got the infinite loop.

Post new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
               `o    O           .oOOOo.            
.oOOo. o O .oOOo. o o
O O O O O.
o oOo o `OOoo.
ooOO .oO o o .oO `O 'o O
o o O O o o O o o
O O o o O O. .O o O O
OooO `OooO' O O `OooO' `oooO' `Oo'oO'

Enter the code depicted in ASCII art style.