Home >Backend Development >C++ >Const Placement in C : `const T` vs. `T const` – Which Should I Use?

Const Placement in C : `const T` vs. `T const` – Which Should I Use?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 11:51:16944browse

Const Placement in C  : `const T` vs. `T const` – Which Should I Use?

Why "const T" and "T const" Are Both Valid, and Which Should You Use?

In C , the const keyword can be used to prevent modification of an object or pointer. Surprising to some developers, the syntax can vary:

const Object* obj; // can't change data
Object* const obj; // can't change pointer
const Object* const obj; // can't change data or pointer
Object const *obj; // same as const Object* obj;

The question arises as to which syntax came first and why both are correct.

Historical Origin of Const Placement

The language grammar for C and C allows for a left-to-right parser, meaning the compiler reads input from left to right and processes tokens as it encounters them.

In parsing the declaration, when the token is consumed, the declaration state changes to a pointer type. If const encounters the first, the qualifier applies to the pointer declaration; if it encounters it before the *, the qualifier applies to the referenced data.

Since the semantic meaning does not change due to the position of const, both placements are accepted.

Implications for Function Pointers

A similar situation arises with function pointers:

  • void * function1(void) declares a function to return a void pointer.
  • void (* function2)(void) declares a function pointer to a function that returns void.

Once again, the left-to-right parser interpretation is evident in the syntax.

Preferred Usage

Ultimately, there is no clear preference for one syntax over the other. The choice should be made based on readability and developer preferences.

However, if consistency with the syntax of pointers and function pointers is desired, using const to the left of the referenced type may be more appropriate:

const Object* obj; // no change to obj pointer or value
Object const *obj; // no change to obj pointer or value

The above is the detailed content of Const Placement in C : `const T` vs. `T const` – Which Should I Use?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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