I’m trying to figure out why even though the local variable i is never intialized in this C program, many systems will print out 0 1 2 3 4 5 6 7 8 9 Can someone explain why this is? Any help is appreciated!
void foo() {
int i;
printf("%d ", i++);
}
int main() {
int j;
for (j = 1; j <= 10; j++) foo();
}
The behavior is undefined. The statistics are irrelevant. It might be because of the layout and the initialization of the stack, but it might be for any other reason as well.
For example, assuming:
iis allocated on the stack and not as a register.In such case
iwill refer to the same place on the stack each time, will start as 0 and the same place on the stack will be incremented each time by one.