c++ - Is const a lie? (since const can be cast away) -


possible duplicate:
sell me on const correctness

what usefulness of keyword const in c or c++ since it's allowed such thing?

void const_is_a_lie(const int* n) {      *((int*) n) = 0; }  int main() {     int n = 1;     const_is_a_lie(&n);     printf("%d", n);     return 0; } 

output: 0

it clear const cannot guarante non-modifiability of argument.

const promise make compiler, not guarantees you.

for example,

void const_is_a_lie(const int* n) {      *((int*) n) = 0; }  #include <stdio.h> int main() {     const int n = 1;     const_is_a_lie(&n);     printf("%d", n);     return 0; } 

output shown @ http://ideone.com/ejogb is

1

because of const, compiler allowed assume value won't change, , therefore can skip rereading it, if make program faster.

in case, since const_is_a_lie() violates contract, weird things happen. don't violate contract. , glad compiler gives keeping contract. casts evil.


Comments

Popular posts from this blog

How do you change vbulletin's home page to the forums instead of the default (CMS or Activity Stream)? -

java - stack overflow exception on xml transformation -