Constant pointers

Pointers can be declared as const which, depending on where you apply it, means that the memory the pointer points to is read-only through the pointer, or the value of the pointer is read-only:

    char c[] { "hello" }; // c can be used as a pointer     *c = 'H';             // OK, can write thru the pointer     const char *ptc {c};  // pointer to constant     cout << ptc << endl;  // OK, can read the memory pointed to     *ptc =  'Y';          // cannot write to the memory     char *const cp {c};   // constant pointer     *cp = 'y';            // can write thru the pointer     cp++;                 // cannot point to anything else

Here, ptc is a pointer to constant char, that is, although you can change what ptc points to, and you can read what it points to, you cannot use it to change the memory. ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.