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.
const
is modifying *
(pointer) rather than int
?const
applies to?*
?Assuming you always place const
to the right of the type, you can read a variable declaration as a sentence from right to left:
int const x; // x is a constant int
int *const x; // x is a constant pointer to an int
int const *x; // x is a pointer to a constant int
int const *const x; // x is a constant pointer to a constant int
This still works if you put const
to the left of a type, but requires a bit more mental effort. Note that this works just as well with pointers-to-pointers (and higher order constructs):
int *const *const x; // x is a constant pointer to a constant pointer to an int
The compiler generally reads the type from right-to-left, so:
T const& const
Would be read as:
const (a constant)
& (to a reference)
const (to a constant)
T (of type T)
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:
const T& const
The above is read as:
const (a constant)
& (to a reference)
const T (to a constant of type T)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With