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?
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 const
ness 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With