We have the following statement from Stephen Prath's book - C ++ Programming Language (6th edition). Page 330:

You can assign the address of both constant and non-constant data to a pointer to a constant, assuming that the data itself is not a pointer, but you can assign the address of non-constant data only to a non-constant pointer.

In my understanding, the following things are available, which coincides with the first part of the author's opinion:

const int a = 5; int b = 6; const int * ptr = &a; //Допустимая операция, невозможно изменить значение a через указатель и переменную a. const int * ptr2 = &b; //Допустимая операция, невозможно изменить значение b через указатель, но возможно через переменную b. 

However, part of the statement about “but assigning the address of non-constant data is allowed only to a non-constant pointer” causes a misunderstanding, according to the author’s logic the following action is unacceptable:

 int a = 5; int * const ptr = &a; //Недопустимо, так как указатель константный, указывает на не константный тип. 

However, this code is successfully compiled, which seems to me quite logical, because as a result we get a pointer without the possibility of changing the address, but nothing prevents to change the value of the variable through the pointer (* ptr).

Actually the question is what the author is trying to convey and what I misunderstood from his statement?

    2 answers 2

    The author had in mind in the second part of the statement the following.

    If you have the following ads

     int x; const int cx; int *p; 

    then you can write

     p = &x; 

    but you can't write

     p = &cx; 

    The constancy of the pointer itself is not discussed in this quote. Just a bad translation takes place, that a pointer to non-constant data is called a non-constant pointer. :)

    As for your example

     int a = 5; int * const ptr = &a; 

    then, if you approach strictly, then there is no assignment operation. Here is the initialization of a constant object. And if you use really assignment, the compiler will give an error message.

    For example,

     int a = 5; int * const ptr; ptr = &a; 

    This code snippet will not compile because the constant pointer must be initialized during the declaration, and, moreover, it cannot be assigned a value.

    • Thanks, and assumed as you wrote. All the same, there is an error in the translation of the book. - IgrikXD
    • @IgrikXD This inaccuracy is also allowed in colloquial speech. Understanding depends on the context. For example, the links themselves cannot be constant, but everywhere, even in the standard, the everyday reference "constant link" sometimes slips. :) - Vlad from Moscow

    The author wanted to say this:

     const int ci = 0; int i = 0; const int *cptr; int *ptr; int main(){ cptr = &ci; //ok cptr = &i; //ok ptr = &ci; //error: invalid conversion from 'const int*' to 'int*' ptr = &i; //ok }