Reputation: 6326
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?
Upvotes: 6
Views: 255
Reputation: 664
I am reading K&R about logic operators,let me quote the origin words of book,which can explain your question. "Expressions connected by && or || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known." Have a good understanding of these,the outputs wont puzzle.
Upvotes: 2
Reputation: 1
You really should learn to use a debugger like e.g. gdb
and to compile with warnings and debugging info like gcc -Wall -g
(assuming a Linux system). A recent gcc
with -Wall
gives you a warning about value computed is not used before the &&
operation.
The increment part of your for
loop is strange. It is i++ && iterator++
(but it should be i++, iterator++
instead).
When i
is 0 (on the first iteration), i++
gives 0 as result, so it is false, so the iterator++
is not executed.
Upvotes: 3
Reputation: 121961
The result of i++
is the current value of i
which is zero on first iteration. This means iterator++
is not executed on first iteration due to short circuting (the right-hand side of &&
is only executed if the left-hand side is "true").
To fix you could use the comma operator (as already suggested or) use ++i
which will return the value of i
after the incremement (though comma operator is more obvious that both must always be evaluated).
Upvotes: 5
Reputation: 129001
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 to 0
. &&
short-circuits, so iterator++
is not executed the first time.
To fix this, you could use the comma operator which unconditionally evaluates both, rather than the short-circuiting &&
.
Upvotes: 11