Is cast from (pointer to const) to (pointer to non const) invalid C ++?

I am sure that the following code should not compile. But in g ++ it compiles! See compile it at http://codepad.org/MR7Dsvlz .

The code:

#include <iostream> using namespace std; int main() { int x = 32 ; // note: if x is, instead, a const int, the code still compiles, // but the output is "32". const int * ptr1 = & x ; *((int *)ptr1) = 64 ; // questionable cast cout << x ; // result: "64" } 

Is g ++ error compiling this?

+8
c ++ casting pointers const g ++
source share
3 answers

Not. According to ยง5.4.4 of the C ++ standard, castings that can be performed by a C-style application are as follows:

 โ€” a const_cast (5.2.11), โ€” a static_cast (5.2.9), โ€” a static_cast followed by a const_cast, โ€” a reinterpret_cast (5.2.10), or โ€” a reinterpret_cast followed by a const_cast 

This is commonly known as "dropping const -ness," and the compiler will be inconsistent with that part of the standard if it does not compile this code.

As ildjarn points out, modifying a const object by discarding const ness is undefined behavior. This program does not demonstrate undefined behavior, because although the object pointed to by a pointer to const , the object itself is not const (thanks R. Martigno and eharvest for correcting my poor reading).

+9
source share

Not. g ++ is not an error compiling your code. the action you have taken is valid.

(int *)ptr1 is c cast. the equivalent in C ++ is const_cast<int*>(ptr1) . the second style is read more clearly.

but the need to do this cast (to change a constant variable) shows a design problem.

+3
source share

The line *((int *)ptr1) = 64 equivalent to *(const_cast<int*>(ptr1)) = 64 . const_cast is the first cast that occurs when using musical notation.

+1
source share

All Articles