8

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?

2
  • If you want to cast away constness (and you're sure its allowed) the idiomatic c++ way to do it is with const_cast<int*>(ptr1) - although the C cast will work too, as you've just seen. Commented Dec 20, 2011 at 2:41
  • 1
    This helpful to read: stackoverflow.com/questions/357600/is-const-cast-safe Commented Dec 20, 2011 at 2:41

3 Answers 3

10

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).

Sign up to request clarification or add additional context in comments.

11 Comments

"No." - So g++ should have compiled the code? "compiler would be non-conformant to that part of the standard if it did not compile that code." - So g++ is conformant to that part of the standard?
@noshenim your question was "Is g++ in error by compiling this?" to which I replied "No". So g++ should, and does, compile the code, and it conforms to that part of the standard.
Noshenim, you asked contradictory questions. Any yes answer to your title question was a no answer to the body question. Please be more careful next time.
@ildjarn ok, added a note about that.
But the object being modified is not const. The object being modified is the int x = 32 ;.
|
3

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.