Home >Backend Development >C++ >Should You Return `const` Values in C ?

Should You Return `const` Values in C ?

DDD
DDDOriginal
2024-12-13 05:00:161028browse

Should You Return `const` Values in C  ?

Why Use Const Value Returns?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn