C/C++ declarations: Which among the following lines are declarations (not definitions) — 1) extern int x; 2) float square(float x) { /* ... / } 3) double pow(double, double);

Difficulty: Easy

Correct Answer: 1 and 3

Explanation:


Introduction / Context:
Correctly distinguishing between declarations and definitions shapes how you structure headers and source files. Declarations introduce names and types; definitions allocate storage or provide function bodies. This question asks you to classify three common patterns you will encounter in real projects.


Given Data / Assumptions:

  • 1) 'extern int x;'
  • 2) 'float square(float x) { / body */ }'
  • 3) 'double pow(double, double);'
  • Standard C/C++ rules apply.


Concept / Approach:

  • For objects: 'extern' declares without defining (no storage).
  • For functions: a prototype with a semicolon is a declaration; a body enclosed in braces is a definition.
  • Therefore, 1 and 3 are declarations; 2 is a definition.


Step-by-Step Solution:

Line 1 → declaration only (no storage allocated).Line 2 → function body present → definition.Line 3 → prototype only → declaration.


Verification / Alternative check:

If you place 1 and 3 in a header and compile multiple translation units, linking succeeds provided there is exactly one definition of 'x' and of the function elsewhere.


Why Other Options Are Wrong:

  • 2: Contains a body; it is a definition, not a mere declaration.
  • Single-choice options miss that two items are declarations.


Common Pitfalls:

  • Putting definitions in headers can cause multiple-definition errors.
  • Forgetting that functions always have external linkage by default unless qualified (e.g., 'static').


Final Answer:

1 and 3

More Questions from Declarations and Initializations

Discussion & Comments

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