Reputation: 2002
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?
Upvotes: 8
Views: 7336
Reputation: 979
No. g++ is not in error by compiling your code. the cast you have done is valid.
(int *)ptr1
is a c cast. the equivalent in c++ is const_cast<int*>(ptr1)
. the second style is clearer to read.
but, the need to do this cast (to modify a const variable) shows a problem in the design.
Upvotes: 3
Reputation: 75150
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).
Upvotes: 10
Reputation: 17587
The line *((int *)ptr1) = 64
is equivalent to *(const_cast<int*>(ptr1)) = 64
The const_cast
is the first cast that is performed when you use the cast notation.
Upvotes: 1