Rave
Rave

Reputation: 843

extern variables in C and their scope

I am trying to understand this code:

#include<stdio.h>
int main()
{
  extern int a;
  printf("%d\n", a);
  return 0;
}
int a=20;

When I run it, the value of a is 20. Yet this should be impossible, since the global variable a is defined at the bottom.

Upvotes: 1

Views: 154

Answers (3)

Linus Kleen
Linus Kleen

Reputation: 34632

Initialization of global variables occurs before main() is called.

So even if the initialization a = 20 is located beneath the implementation of main(), it's always executed first, so it can be used at program start (assuming you fittingly declared the variable in scopes where it's to be used using extern int a).

Upvotes: 1

NPE
NPE

Reputation: 500317

An extern declaration can only be used with variables that are global. It tells the compiler that the global variable is defined elsewhere, and asks the linker to figure it out.

In your code, extern int a refers to the a defined at the bottom of your example. It could have been equally well defined in a different translation unit.

As others have pointed out, the initialization of a takes place before main() is entered.

Upvotes: 3

Mahesh
Mahesh

Reputation: 34625

Not a problem. By declaring the variable as extern you are promising the linker it is defined else where part of current or other source files at global scope.

Upvotes: 2

Related Questions