That is a naughty example. The
"sample text"
is a
string literal constant. Those bytes will be in a memory area that must never be written to.
Your 'c' and 'str' are automatic variables and their content is stored in stack memory. That can be written to.
When you qualify a variable with
const
qualifier you ask the compiler to shout a warning, if you (accidentally) try to modify the value of that variable later in the code.
Your example first correctly says that whatever the 'c' points to shall not be modified.
However, on the next step you explicitly discard that safe-guard (with const_cast).
Luckily, you don't attempt to modify the memory pointed to by 'str'.
Earlier standard did allow pointing to string literal constants without the 'const'.
Note that
char * c = "sample text";
now yields:
In function 'int main()':
11:14: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] |
Old library functions (which do not modify via pointer) lack the const on their parameter list as it was not required. Hence,
1 2
|
const char * c = "sample text";
print ( c ); // error
|
In function 'int main()':
12:13: error: invalid conversion from 'const char*' to 'char*' [-fpermissive] |
Your example shows how to call such function (if you really must).
Pointer has a value, like any variable. That value is a memory address.
If pointer is const, then you cannot change the value. You cannot change where the pointer points to.
Pointer points to some memory area. When you
dereference pointer, you access the value in that memory.
1 2 3 4 5 6 7
|
char line[] = "sample text"; // array 'line' is in stack and contains text
const char * c = line + 2; // pointer c points to 'm' in "mple text"
++c; // we can modify the pointer. Now it points to 'p' in "ple text"
*c = 'a'; // error: cannot assign to const memory
char * str = const_cast<char*>( c ); // str points to 'p' too.
*str = 'a'; // ok. modifying element of array 'line' is fine
// line now contains "samale text"
|