Home > Backend Development > C++ > Const References in Function Arguments: `const T&` or `T const&`?

Const References in Function Arguments: `const T&` or `T const&`?

Susan Sarandon
Release: 2024-11-20 17:03:15
Original
543 people have browsed it

Const References in Function Arguments: `const T&` or `T const&`?

Const Reference in Function Arguments: Before or After Type-Specifier?

In C , the placement of the const reference in function arguments can raise questions. Consider the following two code snippets:

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

Semantically, there is no difference between these two arguments. The language treats them as the same type, both referring to a constant reference to an object of type Fred.

Stylistic Considerations:

However, when it comes to style, the preferred usage varies among programmers.

  • const T&: This is the style used in Stroustrup's "The C Programming Language" and also in the C standard itself.
  • T const&: This style is less commonly used but may be preferred by some for consistency with right-to-left parsing rules, considered a good practice in C .

Right-to-Left Parsing:

According to the right-to-left parsing rule, qualifiers (such as const) should be applied to the type on their left. This would support the use of T const&.

However, it's important to note that const T& can also be parsed effectively right-to-left. It indicates a reference to a constant value of type T. Furthermore, the ambiguity of T const* (which could potentially be interpreted as "pointer constant to T" instead of "pointer to constant T") makes const T& the more unambiguous choice.

Practicality:

In terms of readability and common usage, const T&/const T have gained significant momentum over T const&/T const. This may be due to the prevalence of these styles in widely recognized sources like Stroustrup's book and the C standard. Adhering to commonly accepted practices can enhance code readability.

The above is the detailed content of Const References in Function Arguments: `const T&` or `T const&`?. 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