Const-correctness for function parameters in C++: which statement is correct? Focus on what it means to accept constants and the restrictions on modification.
-
AC++ enables to define functions that take constants as an argument.
-
BWe cannot change the argument of the function that that are declared as constant.
-
CBoth A and B.
-
DWe cannot use the constant while defining the function.
Answer
Correct Answer: Both A and B.
Explanation
Introduction / Context:Const-correctness helps express intent and prevents accidental mutation. It applies to parameters (e.g., const int, const T&, const T*), return types, and member functions. This question checks basic understanding of accepting “constant” arguments and the promise not to modify them.
Given Data / Assumptions:
- “Take constants as an argument” means parameters may be declared const-qualified where meaningful.
- Modifying a parameter declared const is ill-formed.
- We are not referring to top-level const copies that can still be shadowed; we focus on the prohibition against mutation of the const-qualified entity.
Concept / Approach:Declaring parameters as const (e.g., const T& param) expresses that the function will not modify the object referred to. Pointers to const (const T* p) limit mutation through that pointer. Such declarations are core C++ usage. Therefore, it is correct that functions can accept const-qualified parameters and that those const-qualified parameters cannot be modified within the function body.
Step-by-Step Solution:1) Example: void f(const std::string& s) { /* cannot modify s / }2) Attempting s.append("x"); would be ill-formed because s is const-qualified.3) Example with pointer: void g(const int p) { /* *p = 5; // ill-formed */ }4) These patterns directly support statements A and B.
Verification / Alternative check:Compile examples that attempt to mutate const-qualified parameters; the compiler issues errors preventing changes, proving the rule.
Why Other Options Are Wrong:“We cannot use the constant while defining the function” is meaningless/false; const is commonly used in function signatures.
Common Pitfalls:Confusing top-level const on by-value parameters (which protects the local copy only) with const references/pointers that protect the underlying object.
Final Answer:Both A and B.