int i; int *ip; int * const cp = &i; const int ci = 7; const int *cip; const int * const cicp
= &ci;
// // // // // //
just an ordinary integer uninitialized pointer to integer constant pointer to integer constant integer pointer to constant integer constant pointer to constant integer
The following assignments are valid:
i = ci; *cp = ci; cip = &ci; cip = cicp; // assign constant integer to integer // assign constant integer to variable which is referenced by constant pointer // change pointer to constant integer // set pointer to constant integer to reference variable of constant pointer to constant integer // // // // // cannot change constant integer value cannot change constant integer referenced by pointer cannot change value of constant pointer this would allow to change value of constant integer *cip with *ip
The following assignments are invalid:
ci = 8; *cip = 7; cp = &ci; ip = cip;
When used with references some peculiarities must be considered. See the following example program:
int main() { const int ci = 1; const int &cr = ci; int &r = ci;
// create temporary integer for reference
// cr = 7; // cannot assign value to constant reference r = 3; // change value of temporary integer cout << "ci == << ci << r == " << r;
What actually happens is that the compiler automatically creates a temporary integer variable with value of ci to which reference r is initialized. Consequently, when changing r the value of the temporary integer is changed. This temporary variable lives as long as reference r. Reference cr is defined as read-only (constant reference). This disables its use on the left side of assignments.