It ran well on VC++ 6.0 and gave wierd outputs:[Output]Value of x = 10 at address= 0x12ff7cx=5 at address =0x12ff7cNew x=5 at address =0x12ff7cValue of x = 20 at address= 0x12ff7c

Isnt that wierd and wrong? Explain this behaviour.

Answer:The code results in an undefined behaviour.Explanation: It does not work. It just seems to work. Here is the why and how:

You have declared the variable as a const int. So, when you use the address-of operator on this variable it returns a const int * as compared to a normal int variable in which case it return a normal int *. Now, what you are doing is you got the const int * and then you are using the C-style cast (int *) to cast the const int * to a int *. This is the problem. This is where the undefined behaviour is exposed. You forced the pointer to be converted to an int * and use it to modify the original const object. However, the compiler is free to store the constants whereever it wants which might even be a read-only memory location. And if you try making any changes to it, the results are said to be undefined according to the standards. This could probably work, not do anything or even crash.

Instead of printing what is there with 'x', the compiler optimizes the code. The compiler knows that you have defined x as a const int and you have initialized it with 5. So, it is at its own free-will to use optimization and take the value to be printed from this constant rather than using the variable x and dereferencing from its memory location. Here's a quote I like:

"The const keyword can't keep you from purposely shooting yourself in the foot. Using explicit type-casting, you can freely blow off your entire leg, because while the compiler helps prevent accidental errors, it lets you make errors on purpose. Casting allows you to "pretend" that a variable is a different type."

Even I am not very much aware (until now) of the assembly language but I guess this snippet is easy enough to get a feel about what things are happening. The locations marked in black are the one's important to us. Instead of dereferencing x and taking the value from its address, as a optimization techniques the compiler simply pushes in a constant value 5 and uses it while (or even when) there is a different actual value at the storage location of x.

Hence, people! just beware of landing up with code where you cause the undefined behaviour show up. They may look very convincing and correct and that leads to a buggy code very hard to fix. Hope you all liked and enjoyed this post.