I am having little difficulty in figuring out following piece of simple for loop code in C.
int j=20;
for(int i=0, j; i<=j ; i++, j--)
printf("i = %d and j = %d \n",i,j);
Prints output as
i=0 and j=2
i=1 and j=1
Why it does not starts with j=20 and rather prints j=2 and stops after j=1.
But when I use this code
int j=20;
for(int i=0, j=20; i<=j ; i++, j--)
printf("i = %d and j = %d \n",i,j);
It starts properly with
i=0 and j=20 upto ... i=9 and j= 11
Is there something that I am missing ?
You are. Declaring j inside of the for construct creates a new (scoped) j, which has a value different from the outer. If you fail to initialize it, you get whatever crap happened to be in memory when allocated.
Variables like this are called “automatic” variables, and are allocated on the program’s stack. As you need one, more stack space is allocated. When they go out of scope (really when the function returns), they are cleaned up by popping them all back off.
When the next bit of automatic storage is needed, the same thing happens and you then get whatever bit pattern happened to be left over on the stack as your new variables value.