GTO wrote:
But it does not work. i stays 10. *(int *)&i has no effect on i.
The expression '*(int*)&i = 11' has undefined behavior (i.e. it can
cause the system to crash, have the effect of assign '11' to 'i',
or whatever else might happen: it is illegal (i.e. causes undefined
behavior) to cast away constness for an object which actually is a
'const' object (as is the case for 'i'). You can only cast away
constness from pointers or references declared as refering to a
'const' object but actually refer to a non-const object.
You should use 'const_cast<>()' for modifying constness of objects
explicitly. Of course, the compiler should complain about the
particular attempt.
Note that 'const int i = 10' actually is a constant expression:
any use of 'i' in the remainder of the program will almost certainly
be replaced by '10' at compile time! Thus, changing the location
where 'i' is stored will not have any effect - except that the
attempt may cause the system to crash as 'i' is likely to be stored
in write protected memory.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting