-3

what should be the result of the following lines?

const int ci=10;
int * ip=(int *)&ci;
(*ip)=90;

we had two rules, constants can not be changed and changing a part of memory directly using * operator must change the contents of that part of memory. but when I try to print these variables I face something like this:

cout<<ci<<' '<<(*ip)<<endl;
// output: 10 90

how can we explain this?

Aslan
  • 91
  • 5

2 Answers2

4

Oh, it's just a optimization tech named constant folding used by your compiler.

Because, you tell the compiler that ci is a constant int, and so , it trusts you and replace all the reference of ci with 10 when it's compiling your code, so if you cout<<ci, you will get a 10 displayed, this is not because the memory occupied by ci does not change, just because the compiler have replace ci with 10 wherever ci is used!

But, you change the memory through a impolite way, the compiler does not realize the fact!

So, the "constant" keyword is not a strictly constraint, but just a contract between programmer and compiler

Zhiwei Chen
  • 312
  • 2
  • 11
1

Nothing "should" be the result.

Anything "may" be the result.

Undefined behavior is undefined for a reason. Constant variables may be handled in unexpected ways by your compiler. Many compilers may create the variable on the stack, letting you change them. Others may optimize with Copy-on-Write mechanics.

You may get the same number, you may get different numbers, you may get a segfault, you may modify read-write data that is being shared with other const variables because it's not expected to change. Undefined is undefined. Explaining it is a fool's errand.

Taywee
  • 1,313
  • 11
  • 17