0
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?

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
user5248102
  • 21
  • 1
  • 4

3 Answers3

5

There are two cases to consider:

  • If the local variable is static, it is initialized with zeros; static variables of pointer type are set to NULL
  • If the local variable is automatic, it is not initialized at all. Reading from such variable without assigning to it first is undefined behavior.
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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.

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
  • You correctly say "No one can guarantee what value will be on the stack at the beginning of the program". But, on almost _all_ systems, the initial value will be zero. (For various reasons: e.g. a previous program may have left a password in memory.) – Joseph Quinsey Oct 01 '19 at 20:55