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?
&&
operator. If the left hand expresion is 0, then the right hand expression will not be evaluated at all. Read this, andd/or google c operator short circuit – Disfavorfor(i=0; i<size; i++) { if(oneOrZero[i] == 0) { break; }
You can even introduce abool found
variable for extra readability:for(int i=0; i<size && !found; i++) { if(oneOrZero[i] == 0) { found=true; }
– Sunsetnumber_of_bugs_caused_by_post_increment++;
. Irony intended. – Literality