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
Release: 2024-11-15 10:52:02
Original
241 people have browsed it

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) {
...
}
Copy after login
int foo2(Fred const &arg) {
...
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template