Comments on Loopy C Puzzle
Ryan said:
int i;
for (i = 0; -i < 6; i--) {
printf(".");
}
Sean said:
Changing the loop condition to i ^= 6;
is another solution.
Ryan said:
Ah-ha, a tricky one:
int i;
for (i = 0; i ^= 6; i--) {
printf(".");
}
Ryan said:
Ah, Sean beat me to it. :(
Martin DeMello said:
for (i = 0; i + 6; i--)
will stop when i + 6 = 0.
John Tromp said:
The value in variablei
decrements toINT_MIN
after|INT_MIN| + 1
iterations.
No; i decrements to INT_MIN
after |INT_MIN|
iterations. For example,
if i
were a signed 1-bit integer,
making INT_MIN
equal to -1
,
than i
becomes -1
upon
executing --i
after the first iteration.
Of course, you're correct that |INT_MIN| + 1
dots are
output, due to the extra (and final) iteration starting with i
= INT_MIN
.
Susam Pal said:
John, You are absolutely right. Thank you for taking a close look at this post and reporting the off-by-one error in my explanation. I have updated the post now to correct it.
Ryan said: