I have stumbled upon a piece of code that generates some interesting results while debugging someone else’s program.
I have created a small program to illustrate this behavior:
#include <stdio.h>
int main()
{
char* word = "foobar"; int i, iterator = 0;
for (i = 0; i < 6; i++ && iterator++)
printf("%c", word[iterator]);
return 0;
}
I know that this is not the right way to print a string. This is for demonstration purpose only.
Here I expected the output to be “foobar”, obviously, but instead it is “ffooba”. Basically it reads the first character twice, as if the first time iterator++ is executed nothing happens.
Can anyone explain why this happens?
The thing is
iterator++actually isn’t executed the first time. The++operator returns the current value of a variable and then increments it, so the first time through,i++will be equal to0.&&short-circuits, soiterator++is not executed the first time.To fix this, you could use the comma operator which unconditionally evaluates both, rather than the short-circuiting
&&.