Difficulty: Medium
Correct Answer: The program fails at link time with an undefined reference to i, because i is declared extern but never defined in any translation unit
Explanation:
Introduction / Context:
This question tests your understanding of storage class specifiers, the extern keyword, and how the linker resolves global symbols. It also touches on the fact that sizeof operates on types and objects, not on their storage locations.
Given Data / Assumptions:
Concept / Approach:
The extern keyword in this context tells the compiler that the variable i has external linkage and that its definition will be provided in some other translation unit. The compiler uses this information to compile references to i, but it does not allocate storage. When the program is linked, the linker must find exactly one definition of i. Because no such definition exists, the linker reports an undefined reference error. The expression sizeof(i) can be evaluated using the known type int, but the assignment i = 20 requires that storage for i actually exist, so the missing definition is a fatal problem.
Step-by-Step Solution:
Step 1: The compiler sees extern int i; and records that i is an externally defined int.Step 2: The compiler generates code for i = 20; and sizeof(i) using the type information, assuming that a definition will exist at link time.Step 3: During linking, the linker attempts to resolve the symbol i.Step 4: Because there is no definition such as int i; in any object file, the linker reports an undefined symbol or unresolved external for i.Step 5: The executable is not produced, so nothing runs and no output appears.
Verification / Alternative check:
Compiling this code as a standalone program on a typical toolchain produces a link-time error such as "undefined reference to i". If you add a global definition int i; outside main, the program links and runs, printing the size of int.
Why Other Options Are Wrong:
Option A ignores the requirement for a definition and incorrectly suggests successful linking.Option C is incorrect because sizeof works with extern variables; sizeof is based on type, not storage location.Option D mentions a runtime crash, but the program never reaches runtime because the link step fails.
Common Pitfalls:
Many learners think extern both declares and defines storage, which is not true. extern at block scope usually only declares the variable. A separate definition without extern is required in exactly one translation unit.
Final Answer:
The correct description is The program fails at link time with an undefined reference to i, because i is declared extern but never defined in any translation unit.
Discussion & Comments