Thursday, April 07, 2005

Constant confusion

There's so much confusion about const variables in C++. Yeah, they're meant to remain constant throughout their existance. But some people can always find smartass ways to fool the custodian compiler.

const int a = 10;
// Hey guys, I'm const. No one can ever change me!

"Just you wait const a, you won't be const anymore when I'm through with you! Just you wait and see!!!!"

int *ptr = const_cast< int * >(&a);
*ptr = 20;
// na na na naaaeh - You're modified dude!

"What's this guy trying to do?! He must be crazy to think that he can modify me! A const variable. Just wait till you see him watch the results :-)"

std::cout <<  a;

"What the faaak??!! It must have been 20 and not 10!!!! How the hell can this be?!?!"

Simple. Usually the compilers never allocate memory for const variables. They're held in the compile's symbol table. But when some smartass takes the address of a const variable, the compiler just allocates an int and provides him with its address. Just because the compiler provided you with a pointer to the const variable does not mean you can alter the const variable itself. All accesses to the const variable are substituted by the value held in the compiler symbol table and not the memory location that you managed to get. To be more precise, this kind of a thing is undefined behavior. You canNOT take a pointer to a const variable and hope to alter its value and get away with it all the times.

std::cout << *ptr;

This would give you the altered value(20). But most compilers guarantee constness of the variable if the access is made strictly thru the same variable and not the pointer to it.

Hope most of the confusion is cleared?!
Btw who am I telling this to?! :-)

PS: This has been tried with the GNU C++ compier ver-2.96 and with the Microsoft optimising C++ compiler ver-13.10.3077.

No comments:

Post a Comment

What I want to say is: