Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top