Is const a lie? (since const can be cast away)
c, c++, constants
Solution
`const` is a promise you make to the compiler, not something it 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 at http://ideone.com/Ejogb is
1
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.
Problem
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.