Best const questions in June 2012

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

22 votes

Possible Duplicate:
Sell me on const correctness

What is the usefulness of keyword const in C or C++ since it's allowed such a 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 is clear that const cannot guarante the non-modifiability of the argument.

const is a promise you make to the compiler, not something it guarantees you.

See http://ideone.com/Ejogb

Because of the const, the compiler is allowed to assume that the value won't change, and therefore it can skip rereading it, if that would make the program faster.

In this case, since const_is_a_lie() violates its contract, weird things happen. Don't violate the contract. And be glad that the compiler gives you help keeping the contract. Casts are evil.