Home >Backend Development >C++ >Const Reference in C : Const Before or After the 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:
Others favor T const& (and T const*), based on readability:
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!