Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a 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 does compile! See it compile 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++ in error by compiling this?

like image 635
Gavin Haynes Avatar asked Dec 20 '11 02:12

Gavin Haynes


1 Answers

No. According to §5.4.4 of the C++ standard, the casts that can be performed by a C-style cast are:

— 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 widely known as "casting away const-ness", and the compiler would be non-conformant to that part of the standard if it did not compile that code.

As ildjarn points out, modifying a const object via casting away constness is undefined behaviour. This program does not exhibit undefined behaviour because, although an object that was pointed to by the pointer-to-const, the object itself is not const (thanks R.Martinho and eharvest for correcting my bad reading).

like image 118
Seth Carnegie Avatar answered Sep 28 '22 13:09

Seth Carnegie