Search code examples
c++extern

"extern" keyword usage


I have the following code snippet:

 #include<iostream>

 int main()
 {
     extern int a;
     printf("a = %d", a)
 }
 int a = 10;

Above sample code print 10. My guess was it should print garbage value. Can someone explain this ?


Solution

  • Global variables have static duration and statics are initialized before main runs. Therefore a already has it's value set to 10 by the time printf is called.