Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-24 10:02:12
Original
268 people have browsed it

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

Const Reference in C : Placement Before vs. After Type Specifier

In C , when dealing with const references, there arises a question regarding the placement of the const keyword in relation to the type specifier: before or after? Let's examine the syntax and behavior of these two forms.

Syntax:

  • Const Reference Before Type Specifier:

    int foo1(const Fred &arg) {
    ...
    }
    Copy after login
  • Const Reference After Type Specifier:

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

Behavior:

Both syntaxes result in the same behavior. The language treats const T& and T const& as equivalent types. This applies to both pointer and reference declarations.

Stylistic Considerations:

While there is no functional difference between the two placement options, stylistic preferences vary. However, there are some arguments to be made for preferring const T& (and const T*):

  • Consistency with Standard Texts: const T& is the style used in both the C Programming Language book by Bjarne Stroustrup and the C standard itself.
  • Ubiquity: const T&/const T* is empirically more common in C and C code than its alternative placement.
  • Parsing Ambiguity: Misplacing the asterisk with T const* is a potential issue, while const* T is not valid syntax.

The right-to-left parsing rule often cited in favor of placing const after the type specifier can be subjective. const T& can also be parsed right-to-left as "reference to a T constant."

The above is the detailed content of Const Reference in C : 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