Home > Backend Development > C++ > Const Reference in C : `const T&` or `T const&` – What's the Difference?

Const Reference in C : `const T&` or `T const&` – What's the Difference?

Barbara Streisand
Release: 2024-11-14 18:23:02
Original
589 people have browsed it

Const Reference in C  : `const T&` or `T const&` – What's the Difference?

Const Reference Types in C : Placement of the 'const' Qualifier

In C , there are two ways to declare constant references using the 'const' qualifier:

const Fred &arg;
Fred const &arg;
Copy after login

Semantic Differences

Semantically, these two declarations are equivalent, and the language considers them as the same type. There is no functional difference between passing an argument by const T& or T const&.

Style Considerations

However, when it comes to style, there are different preferences among programmers.

Left-to-Right Parsing

Some programmers advocate for placing the 'const' qualifier after the type (T const&), arguing that it follows the right-to-left parsing rule in C . This ensures that when reading the declaration, the 'const' qualifier is applied to the type, rather than to the reference itself.

Right-to-Left Parsing

Others, however, prefer the const T& syntax, arguing that it reads equally well right-to-left. It can be interpreted as "reference to a T constant". Furthermore, placing the 'const' qualifier before the reference prevents the accidental declaration of a pointer constant, such as 'T* const' which is illegal.

Common Practice

In practice, both styles are widely used. The style preferred by Stroustrup's "The C Programming Language" and the C standard is const T&. However, the style used in K&R's "The C Programming Language" and the C standard is T const*. Ultimately, the choice of style is a matter of personal preference and may also be influenced by the coding conventions of specific organizations.

The above is the detailed content of Const Reference in C : `const T&` or `T const&` – What's the Difference?. 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