C/C++ language basics: Is the statement 'extern int i;' a declaration or a definition?

Difficulty: Easy

Correct Answer: Declaration

Explanation:


Introduction / Context:
In multi-file C/C++ projects, header files commonly contain 'extern' declarations of globals. Understanding how 'extern' changes the meaning of a statement prevents multiple-definition linker errors while allowing many translation units to reference the same variable defined elsewhere.


Given Data / Assumptions:

  • The line in question is 'extern int i;' with no initializer.
  • We are discussing a global-scope variable, not a function.
  • Standard C/C++ linkage rules apply.


Concept / Approach:

  • A declaration introduces a name and its type. Using 'extern' for an object declares it without defining (allocating storage for) it.
  • A definition for a global object allocates storage. Example: 'int i;' or 'int i = 0;'.
  • Exactly one definition with external linkage must appear across the program, while declarations can appear in multiple files.


Step-by-Step Solution:

Classify 'extern int i;' → declaration only (no storage allocated).Recognize that definition would be 'int i;' (or with initialization) in exactly one source file.Thus, the statement is a declaration.


Verification / Alternative check:

Placing 'extern int i;' in a header included in many files compiles; the program links only if one file defines 'int i;' once.


Why Other Options Are Wrong:

  • Definition: Would allocate storage; our line does not.
  • Function: We are not declaring a function here.
  • Error: The statement is valid; it simply declares an external symbol.


Common Pitfalls:

  • Putting a definition (without extern) in a header causes multiple definitions during linking.
  • Confusing 'extern' on variables with function declarations where 'extern' is redundant.


Final Answer:

Declaration

Discussion & Comments

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