He Chen He Chen - 6 months ago 19
C++ Question

Why does assigning to a constant via pointer have no effect?

In the example below, 'ptr' points to the constant variable 'local'. Why does modifying 'local' by assigning '*ptr' not change the value of 'local'?

#include <stdio.h>
int main(void)
const int local = 10;
int *ptr = (int*) &local;

printf("address of local: %p \n", &local);
printf("value of ptr: %p \n", ptr);
printf("Initial value of local : %d \n", local);
printf("Initial value of *ptr : %d \n", *ptr);

*ptr = 100;
//*((int*)&local) = 1000;

printf("Modified value of local: %d \n", local);
printf("Modified value of *ptr: %d \n", *ptr);
printf("address of local: %p \n", &local);
printf("value of ptr: %p \n", &(*ptr));

return 0;

The output:

address of local: 0x7ffd946bd9c4
value of ptr: 0x7ffd946bd9c4
Initial value of local : 10
Initial value of *ptr : 10
Modified value of local: 10
Modified value of *ptr: 100
address of local: 0x7ffd946bd9c4
value of ptr: 0x7ffd946bd9c4

Answer Source

The line:

*ptr = 100;

is undefined behavior. The reason why is because ptr points to a const object. You made this compile by casting away the const-ness, but the language still says that actually modifying an object declared const is illegal: http://en.cppreference.com/w/cpp/language/const_cast.

The presence of undefined behavior basically means that your program could do many different, weird things on different compilers/optimization levels. In short, do not modify const objects, and for now steer clear of const_cast. It's usually a sign of bad design; there are relatively few legitimate uses for it which you'll learn as you go. Here's a link to an example of a rare valid use of const_cast: How do I remove code duplication between similar const and non-const member functions?. This technique removes code duplication, but fundamentally it relies on throwing away const-ness when only the pointer is const qualified, but the underlying object is known to not be const.

The difference between actual const values, and a const aliasing pointer/reference is very important in C++.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download