Pointers
const
const int* const ptr = &value;
- First const (before type): Prevents changing the value when dereferencing
- Second const (after type): Prevents changing the pointer's memory address
Example
int a = 1;
int b = 2;
// const before type
const int* const_before = &a;
const_before = &b; // ALLOWED. Can change memory address
*const_before = 3; // NOT ALLOWED. Cannot change the value
// const after type
int* const const_after = &a;
const_after = &b; // NOT ALLOWED. Cannot change memory address
*const_after = 3; // ALLOWED. Cannot change the value
// both combined
const int* const const_both = &a;
const_both = &b; // NOT ALLOWED. Cannot change memory address
*const_both = 3; // NOT ALLOWED. Cannot change the value
// const in the middle. Same as const after (const_after)
int const * const_middle = &a;
const_middle = &b; // NOT ALLOWED. Cannot change memory address
*const_middle = 3; // ALLOWED. Cannot change the value
Recommended to use
const when passing pointers in functions In general, the const applies to the type on the left.
But when its on the extreme left, the applies to first part of the type. Source: Stackoverflow