In the following code at the end of the program z = 20 & y = 99.
void doit(const int* x)
{
int* nonconst;
nonconst = const_cast<int*>(x);
*nonconst = 99;
}
int main(int argc, char* argv[])
{
const int y = 20;
int z;
doit(&y);
z = y; // Fails
return 0;
}
having looked at the generated assembler code I can see why this is
'failing' as the assembler uses a numeric literal to assign 20 to z on the
failing statement. This is logical & efficient in most cases as y is a
const which can be evaluated at compile time. However, since the facility
has been provided to un-const a const variable (bad programming practice?) I
would have thought that this code should work. I've tried it on Microsoft &
g++ compilers with the same result. I have seen a web site that said that
the result of const_cast in cases like this was undefined. I find the idea
of undefined results in programming utterly abhorrent. We might as well
accept 'nearly working' programs with such constructs as 'do sometimes'
loops etc. Can this 'undefined' result be correct or is it a bug in the
language specification / compilers?
Any comments?
Simon