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