void func();
int main() {
func();
func();
func();
}
void func() {
int a;
printf("%d\n",++a);
}
When I run this C code in GCC compiler I get output as
1
2
3
Why does this happen without using the static
keyword?
void func();
int main() {
func();
func();
func();
}
void func() {
int a;
printf("%d\n",++a);
}
When I run this C code in GCC compiler I get output as
1
2
3
Why does this happen without using the static
keyword?
There are two cases to consider:
static
, it is initialized with zeros; static
variables of pointer type are set to NULL
According to the C Standard (6.7.9 Initialization)
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
and (3.19.2)
1 indeterminate value either an unspecified value or a trap representation
So there is no default value for objects with automatic storage duration. They have indeterminate values.
Take into account that the notions of local variable and of variable with automatic storage duration are different. For example in this program
#include <stdio.h>
int x = 10;
void f()
{
extern int x;
printf( "%d\n", x );
}
int main( void )
{
f();
}
the variable x declared in function f like
extern int x;
is a local variable of the function. But it has external linkage and denotes the same variable as the global. x.
The program output will be
10
This is a very simple program. A local variable is placed on the stack. No one can guarantee what value will be on the stack at the beginning of the program. But since you call the same function which increments the local variable a
, the variable is incremented on the stack. Then you call the same function again so it allocates the same place on the stack which already has the value of a
from the previous time. If you call any other function between func ()
in the int main()
(for example printf
), you will get different results.