I'm attempting to run the following C code
#include <stdio.h>
void myFunc() {
static int a;
int b;
a++;
b = b + 2;
printf("a:%d, b:%d\n",a,b);
}
int main(void) {
myFunc();
myFunc();
return 0;
}
The result I get when compiling on ubuntu with gcc version 5.4.0 20160609 is
a:1, b:2
a:2, b:4
I understand that a, being static, will be zero initialized, but it appears that non-static b is being zero initialized as well. Further, it looks like b is actually being converted to a static variable, since its value is retained for the second call to myFunc.
I'm assuming this has something to do with my compiler/OS because compiling with codepad online (using gcc 4.1.2) gives
a:1, b:2
a:2, b:2
which, while still zero-initializing b for some reason, does not retain the value of b for subsequent calls to myFunc.
1) Why is a non-static variable being zero-initialized? Am I just constantly getting lucky that the compiler assigned to it a memory block that was zero'd?
2) Why does gcc seem to convert b to a static variable in gcc 4 but not gcc 5?
EDIT:
To better illustrate this issue, if I add, say, 6 more calls to myFunc, the resulting output is:
a:1, b:2
a:2, b:4
a:3, b:6
a:4, b:8
a:5, b:10
a:6, b:12
a:7, b:14
a:8, b:16