0

Given this code (from my last post here):

  const int j = 5; // constant object
  const int *p = &j; // `p` is a const access path to `j`

  int *q = const_cast<int *>(p); // `q` is a non-const access path to `j`
  *q = 10;

  cout << *q << endl;

The output is : 10

Is it suppose to be this way ? I thought that this code was supposed to lead to an undefined behavior , since j is a const . Am I wrong ?

Thanks

Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318
  • 2
    So your real question is "Is it allowed for a program with undefined behavior to output `10\n` to the console?" and the answer is *Yes*. – Ben Voigt Jul 14 '12 at 14:52
  • You thought it led to undefined behaviour. It did. Where is the problem? – Konrad Rudolph Jul 14 '12 at 14:55
  • `Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.` So it's an undefined behavior. [Source](http://en.cppreference.com/w/cpp/language/const_cast) – Olwaro Jul 14 '12 at 14:56
  • @Olwaro: Lovely , I won't use it in the future . – JAN Jul 14 '12 at 14:57
  • This almost identical [const_casting question](http://stackoverflow.com/questions/4518630/const-casting-question) ask why the output is **not** changed. – Bo Persson Jul 14 '12 at 15:08

3 Answers3

2

Undefined behavior can be anything -- it could do exactly what you want to it do, or it could destroy the universe. If possible, avoid undefined behavior since I don't really want to be destroyed just because you're too lazy to do things correctly.

Christian Stieber
  • 9,954
  • 24
  • 23
1

http://en.wikipedia.org/wiki/Undefined_behavior

This specifically frees the compiler to do whatever is easiest or most efficient, should such a program be submitted. In general, any behavior afterwards is also undefined. In particular, it is never required that the compiler diagnose undefined behavior — therefore, programs invoking undefined behavior may appear to compile and even run without errors at first, only to fail on another system, or even on another date. When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.

Caesar
  • 9,483
  • 8
  • 40
  • 66
0

It wouldn't take much of an optimizer to realize that

*q = 10;
std::cout << *q;
// not use q anymore

Could be rewritten as

std::cout << 10;

And q can be removed, because now it isn't used.

After that, p and j are not used anymore either, and can be removed as well.

All this assuming you haven't entered any undefined behavior into your program. An assumption the compiler is allowed to make.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203