user4418808
user4418808

Reputation:

Program Flow in C

I was just going through some questions and found this is one though the question asked about declaration and definition which know I understand thanks to stackoverflow.

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

The flow of execution of C program is from top to bottom if it doesn't encounter any control statements, So in the above code extern int a declares a while int a=20 defines a but this statement is even after main() terminated which results in the end of program, So why this code doesn't give any error Like Undefined symbol a ?

Upvotes: 3

Views: 170

Answers (1)

The last int a=20; is not a statement but a definition. So the variable a is initialized before the start of the program.

(On Linux systems running an ELF executable, the a is probably in some data segment, initialized at execve(2) time of your program)

The extern int a; inside main is a declaration of some global symbol (which in your case happens to be the variable a defined later).

You could have put the int a=20; in some other translation unit and build your program by linking both.

Read Levine's book on linkers and loaders

Upvotes: 4

Related Questions