Home >Backend Development >C++ >Should You Return `const` Values in C ?
Problem:
Consider the following code snippet:
const Object myFunc() { return myObject; }
What is the purpose of the const keyword here? While the Effective C Item 3 advocates its use, opinions vary.
Answer:
In the rare scenario where a non-const operation on an object could be performed before assignment, a const value return prevents accidental invocation of such an operation on a temporary.
However, this practice has become outdated. In C 11 and later, it is strongly recommended to return non-const values to fully utilize rvalue references, which are only valid for non-constant rvalues.
In essence, while reasons existed for using const value returns, they are no longer compelling in modern C .
The above is the detailed content of Should You Return `const` Values in C ?. For more information, please follow other related articles on the PHP Chinese website!