I am having trouble finding an intuitive pattern for the way const is used in declarations in the C and C++ languages. Here are some examples:
const int a; //Const integer
int const a; //Const integer
const int * a; //Pointer to constant integer
int * const a; //Const pointer to an integer
int const * a const; //Const pointer to a const integer
In lines 1 and 2, it seems const can come before or after int, which is what it modifies.
- So how, in line 4, does the compiler decide that
constis modifying*(pointer) rather thanint? - What is the rule that the compiler follows for deciding which thing the
constapplies to? - Does it follow the same rule for
*?
The compiler generally reads the type from right-to-left, so:
Would be read as:
So, basically the keyword “const” modifies everything that precedes it. However, there is an exception in the case where “const” comes first, in which case it modifies the item directly to the right of it:
The above is read as:
And the above is equivalent to T const& const.
While this is how the compiler does it, I really just recommend memorizing the cases “T”, “const T”, “const T&”, “const T*”, “const T& const”, “const T* const”, “T& const”, and “T* const”. You will rarely encounter any other variation of “const”, and when you do, it’s probably a good idea to use a typedef.