I can't get my head around why the code below is not working as expected:
#include <stdio.h>
int main() {
int i = 0, size = 9, oneOrZero[] = {1,1,1,1,1,1,1,1,0};
while (i < size && oneOrZero[i++]);
if (i == size) printf("All ones"); else printf("Has a zero");
}
Terminal: All ones.
When incrementing the index inside the loop makes the code run as expected:
#include <stdio.h>
int main() {
int i = 0, size = 9, oneOrZero[] = {1,1,1,1,1,1,1,1,0};
while (i < size && oneOrZero[i]) {i++;}
if (i == size) printf("All ones"); else printf("Has a zero");
}
Terminal: Has a zero.
Could someone explain the difference between these two?
In the first code, when
i
is8
,oneOrZero[i]
will evaluate tofalse
becauseoneOrZero[8]
==
0
, buti
will be incremented to9
anyway, the increment is not dependent on the truthiness of the expression, it will happen as many times as the expression is evaluated.So naturally when
i == size
is evaluated it's9 == 9
, this is, of course,true
, therefore"All ones"
will be printed giving you the wrong output.In the second code
i
is incremented inside the body of the conditional expression, this means it will only be incremented if the condition is met, so wheni
is8
,oneOrZero[i]
will evaluate tofalse
andi
is not incremented, retaining its8
value.In the next line statement
i == size
will be8 == 9
which isfalse
and"Has a zero"
will be printed, giving you the correct output.