Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can casting away constness lead to undefined behavior? [duplicate]

Tags:

People also ask

Do not cast away a const qualification?

Do not cast away a const qualification on an object of pointer type. Casting away the const qualification allows a program to modify the object referred to by the pointer, which may result in undefined behavior.

Is const_cast undefined behavior?

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.

Why does const_ cast exist?

On the opposite end, the reason for const_cast to exist was adapting to old C code that did not support the const keyword. For some time functions like strlen would take a char* , even though it is known and documented that the function will not modify the object.

Can you cast a const?

const_cast can be used to add const ness behavior too. From cplusplus.com: This type of casting manipulates the constness of an object, either to be set or to be removed.


const int a = 10
int *p = (int*) &a;
*p = 20;
printf("a = %d", a);

Is it possible to output either 10 or 20, depending on the compiler?