Where should the default value of a function parameter be specified in C++? Choose the place(s) allowed by the language (avoid duplicating across declarations).

Difficulty: Easy

Correct Answer: Both B or C

Explanation:


Introduction / Context:
Default arguments are part of a function declaration, not something written at the call site. C++ allows you to place them where you declare the function, but you must avoid repeating them in multiple declarations to prevent inconsistencies.


Given Data / Assumptions:

  • You may have a prototype in a header and a separate out-of-line definition in a source file.
  • A definition is also a declaration in C++.
  • The same default should not be written twice in different declarations in the same scope.


Concept / Approach:
You can specify defaults either in the function prototype (declaration) or, if there is no separate prototype, directly in the function definition (which is itself a declaration). Do not specify the same default in both prototype and definition. The call site never supplies the “= value” syntax; that syntax belongs only in declarations.


Step-by-Step Solution:
1) Header pattern: void f(int x = 1); // declaration with default2) Source definition: void f(int x) { /* ... / } // no repeat3) Single-file pattern: void g(int y = 2) { / ... */ } // default in definition (no separate prototype)4) Therefore, the correct answer is “Both B or C”.


Verification / Alternative check:
Move the default from the prototype to the definition and remove it from the prototype; compilation still succeeds as long as one visible declaration at the call site carries the default.



Why Other Options Are Wrong:
Function call: defaults are not written at call sites; they are inserted by the compiler.Picking only B or only C ignores that either location is valid when used singly.



Common Pitfalls:
Duplicating defaults across multiple declarations in headers and sources, risking divergence and ODR issues.



Final Answer:
Both B or C

More Questions from Functions

Discussion & Comments

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