views:

135

answers:

3
+6  A: 

Congratulations, you lied to the the compiler and it bit you.

Casts tell the compiler that you are intentionally breaking the rules and imply that you know what you are doing. C is happy to allow you to shoot yourself in the proverbial foot when you do this.

msw
hmm? Still the same address de-referenced is giving different answer..
bakra
because it's not stored in read-only memory.. 'const' only tells compiler that it should'n be changed
fazo
I don't get ur explanation... see the edit
bakra
+7  A: 

What you have with int const is in fact not a constant but a const qualified object. So if you play games of changing this object through pointer manipulations this might be possible but delivers undefined behavior.

The only integer constants in C are number tokens, integer character constants such as 'a' and enum constants.

Jens Gustedt
+5  A: 

There's not a while lot of mystery here. By using casts to tell the compiler that what you're changing isn't const qualified, you're causing undefined behavior:

6.7.3/5 "Type qualifiers" (C99):

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

Some implementations might have placed the variable z in read only memory and you'd either get no apparent change or some sort of access violation.

In any case, undefined behavior means all bets are off - in your case you're able to see the apparent modification of a const value.

Michael Burr