I'm learning const and pointers playing with examples. From this thread I read that: const char* the_string : I can change the char to which the_string points, but I cannot modify the char at which it points.
int main()
{
const char* a = "test";
char* b = "other";
a = b;
cout << a << endl; //prints "other"
}
Why can I modify at which char a points ?
You can set a
to point at something else since a
is itself not const
: only the data to which it points is const
.
Setting b = a
would not be allowed, since you'd be casting away const
.
If you want to prevent a = b
then write
const char* const a = "test";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.