This part of my code works fine:
#include <stdio.h>
int main(){
//char somestring[3] = "abc";
int i, j;
int count = 5;
for((i=0) && (j=0); count > 0; i++ && j++){
printf("i = %d and j = %d\n", i, j);
count--;
}
return 0;
}
The output as expected:
i : 0 and j : 0
i : 1 and j : 1
i : 2 and j : 2
i : 3 and j : 3
i : 4 and j : 4
Things get weird when I uncomment the char string declaration on the first line of the function body.
#include <stdio.h>
int main(){
char somestring[3] = "abc";
...
}
The output:
i : 0 and j : 4195392
i : 1 and j : 4195393
i : 2 and j : 4195394
i : 3 and j : 4195395
i : 4 and j : 4195396
What’s the logic behind this? I’m using gcc 4.4.1 on Ubuntu 9.10.
jnever gets initialised, because of the short-circuiting behaviour of&&. Since(i=0)evaluates to false,(j=0)never gets executed, and hencejgets a random value. In the first example, that just happens to be zero.You should say
i=0, j=0to achieve what you want.The
i++ && j++has the same problem; it should bei++, j++.Also, this:
is reserving one too few bytes, because of the trailing NUL character in the string – you need four bytes. But if you’re not going to modify the string, you don’t need to specify the number of bytes – you can simply say this:
instead.