C extern and definition order: what does this program print when a global is defined after main? #include<stdio.h> int main() { extern int a; // declaration printf("%d ", a); return 0; } int a = 20; // definition after main is valid

Difficulty: Easy

Correct Answer: 20

Explanation:


Introduction / Context:
Linkage and declaration order in C often confuse newcomers. This example shows that a global can be declared before use and defined later in the same translation unit without issue.



Given Data / Assumptions:

  • extern int a; in main() declares an external integer.
  • A definition int a = 20; appears after main in the same file.
  • Program prints a.


Concept / Approach:
An extern declaration tells the compiler the name and type exist somewhere. A definition provides storage. The linker resolves references to the later definition in the same translation unit just fine. Output is the initialized value.



Step-by-Step Solution:
Compiler sees the declaration, allows usage in printf.Definition after main allocates storage and initializes to 20.Linker binds the reference to that definition.Program prints 20.



Verification / Alternative check:
Placing the definition before or after main() yields the same behavior; what matters is that one definition exists at link time.



Why Other Options Are Wrong:
B/C: The variable is explicitly initialized to 20. D/E: No compile or link error since declaration and definition are consistent.



Common Pitfalls:
Confusing declaration with definition; believing order within a single file restricts visibility (linker resolves it).



Final Answer:
20

More Questions from Declarations and Initializations

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion