Home >Backend Development >C++ >Const Reference in C : Const Before or After the Type Specifier?

Const Reference in C : Const Before or After the Type Specifier?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 10:52:02252browse

Const Reference in C  : Const Before or After the Type Specifier?

Const Reference: Before vs. After Type-Specifier

In C , there is a subtle difference in syntax for declaring a const reference:

int foo1(const Fred &arg) {
...
}
int foo2(Fred const &arg) {
...
}

Both declaration methods produce a constant reference to a Fred object. However, the placement of the const keyword has no semantic impact.

As a Matter of Style

While the behavior of these declarations is identical, there are stylistic preferences to consider.

Some prefer const T& (and const T*), citing:

  • Alignment with Stroustrup's book and the C standard
  • Familiarity among experienced C programmers
  • Common usage in the industry

Others favor T const& (and T const*), based on readability:

  • Consistent right-to-left parsing
  • Reduced risk of misplacing the * or interpreting T const* incorrectly

Right-to-Left Parsing

The right-to-left parsing rule states that declarations should be read from right to left. Therefore, const T& can be interpreted as "a reference to a const T" or "a const T reference." Similarly, T const& can be read as "a const reference to a T" or "a T const reference." Both interpretations are grammatically correct, making the placement of the const keyword less impactful on readability than some argue.

Ultimately, the choice between these declaration styles is a matter of personal preference. Both are syntactically correct and convey the same meaning.

The above is the detailed content of Const Reference in C : Const Before or After the Type Specifier?. 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