Const Data: Two Declared Paths
In C , you can make an object's data or pointer unmodifiable using const. The traditional syntax for this is:
const T *obj; // Pointer to const data T const *obj; // Equivalent to const T*
However, you may have noticed an alternative syntax:
Object const *obj;
This raises the question: why are both syntaxes valid, and when should you use one over the other?
The Birth of Const Data
The positioning of const within type declarations stems from the early days of C. The language grammar defined by Kernighan and Ritchie allowed for const data to be declared as:
const T *obj;
In essence, the C compiler parsed tokens from left to right, applying const to the appropriate type specification based on the token's position.
The Const Qualifier's Application
The position of const within type declarations does not affect the result because const always applies to the declaration to its left. In the case of pointers:
Semantic Equivalence
The underlying reason for this equivalence is that the semantic meaning of the declaration remains the same regardless of const's position. Whether you use const T *obj or T const *obj, you protect the data pointed to by obj from modification.
Function Pointers: A Similar Case
A similar situation arises when declaring function pointers:
void * function1(void); // Function returning void * void (* function2)(void); // Function pointer to a function returning void
Again, the left-to-right parsing of the language syntax allows for these alternative declarations.
Preference and Use Cases
Ultimately, the preference for one syntax over another is subjective. However, it's generally recommended to use:
Regardless of your preference, both syntaxes are valid and semantics remain consistent.
The above is the detailed content of Why Are `const T *obj` and `T const *obj` Both Valid in C , and When Should I Use Each?. For more information, please follow other related articles on the PHP Chinese website!