One of the disadvantages of pass by reference is that the called function may…
2018
One of the disadvantages of pass by reference is that the called function may inadvertently corrupt the caller’s data. This can be avoided by —
- A.
passing pointers
- B.
declaring the formal parameters constant
- C.
declaring the actual parameters constant
- D.
All of the above
Attempted by 466 students.
Show answer & explanation
Correct answer: B
Key idea: To prevent a called function from accidentally modifying the caller’s data when passing by reference, declare the function's formal parameters as const. Explanation and example: Declaring the formal parameter const ensures the function cannot legally change the argument. Correct approach: declare the formal parameter const. Example: void printValue(const int& x) { /* x cannot be modified here */ }
Why passing plain pointers is not enough: a non-const pointer lets the function modify the pointed-to data. Use const Type* if you want pointer-based protection.
Why declaring actual arguments const in the caller does not help: const on the caller-side does not force the function’s parameter to be const; protection must be applied to the formal parameter in the function signature.
Recommended alternatives: use const references (const T&) or pointers to const (const T*), or pass by value if you need an independent copy.
Summary in