Default arguments: which statement is incorrect with respect to declaration and usage sites? Pick the option that violates best practice or standard rules.

Difficulty: Easy

Correct Answer: The default arguments are given in the function prototype and should be repeated in the function definition.

Explanation:


Introduction / Context:
Where you place default arguments affects readability and linkage. The language allows specifying defaults in a declaration; repeating them in multiple places leads to maintenance hazards and can violate the One Definition Rule (ODR) when headers and sources disagree.


Given Data / Assumptions:

  • Declarations may appear in headers; definitions often live in source files.
  • The compiler relies on declarations to form calls during compilation.
  • Global constants are in scope for use as default expressions.


Concept / Approach:
The standard practice is to specify default arguments exactly once—typically in the function prototype (declaration) in a header. They should not be repeated in the out-of-line definition; doing so duplicates information and can cause inconsistencies if values diverge across translation units.


Step-by-Step Solution:
1) Place defaults in a header: void f(int x = DefaultX);2) Define without repeating: void f(int x) { /* ... */ }3) The compiler uses the declaration to substitute missing arguments at call sites.4) Repeating defaults in the definition is discouraged/incorrect and may be ill-formed if it conflicts.


Verification / Alternative check:
Inspect any standard library header: defaults appear in declarations (e.g., ios flags manipulators). Out-of-line definitions omit default values.



Why Other Options Are Wrong:
Global constants as default values are fine.Defaults in the prototype are correct and conventional.The compiler indeed builds calls from the prototype information at the call site.



Common Pitfalls:
Putting different default values in multiple declarations across translation units, causing surprising behavior depending on which declaration a file sees.



Final Answer:
The default arguments are given in the function prototype and should be repeated in the function definition.

More Questions from Functions

Discussion & Comments

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