C/C++ declarations: Is there any difference between the following function declarations—(1) extern int fun(); and (2) int fun();—when no function body is provided?

Difficulty: Easy

Correct Answer: Both are identical

Explanation:


Introduction / Context:
Developers frequently separate function declarations from definitions across header and source files. In that workflow, you often see forms like 'extern int fun();' or simply 'int fun();'. This problem tests your understanding of linkage and what these two declarations actually mean in C/C++ when no function body is provided.


Given Data / Assumptions:

  • Two lines appear without a function body: 'extern int fun();' and 'int fun();'.
  • No parameter list details are given (just empty parentheses).
  • We are reasoning about declarations, not definitions.


Concept / Approach:

  • For functions, the storage class 'extern' is the default; a function declaration without 'static' or 'inline' already has external linkage.
  • Therefore, writing 'extern int fun();' versus 'int fun();' communicates the same linkage and does not allocate storage or provide a body.
  • A definition would be 'int fun() { /* body */ }' and it appears exactly once per program (per the One Definition Rule in C++).


Step-by-Step Solution:

Identify both statements as declarations (no body present).Recall: function declarations have external linkage by default unless otherwise specified (e.g., 'static').Conclude that adding 'extern' to a function declaration is redundant; the two lines are semantically identical.


Verification / Alternative check:

Place each line in a header and compile with a definition in a .c/.cpp file. The program links and runs the same in both cases.


Why Other Options Are Wrong:

  • No difference, except in another file: Location does not change the meaning; both are still declarations.
  • 'int fun();' is overridden by 'extern int fun();': There is no overriding in declarations; they are equivalent.
  • None of these / different linkage: Incorrect because both declare the same external linkage.


Common Pitfalls:

  • Confusing function declarations with variable declarations ('extern int x;' behaves differently from 'int x;').
  • Assuming empty parentheses mean 'no parameters' in C; strictly, 'void' should be used in C to indicate no parameters (C++ treats it as no parameters).


Final Answer:

Both are identical

Discussion & Comments

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