Interview Question
Country: India
Thanks for your value added comment but i do not get why the "*ptr = *ptr+10;" get changed and its still hold the same address as 'a' variable.
Because there's no "a" variable. After the code compiles, it looks like
cout << 0 <<" Address a "<< some_number <<endl;
cout <<*ptr<<" Address in ptr "<<ptr<<endl;
The references to "a" might be being completely removed at compile time. So then it could well be that ptr = some_number (that is &a, determined at compile time), and it could well be that *ptr = 10, but the 0's baked right into the code as a literal. There is no "a". All expressions using "a" have been rewritten with the literal constant.
You can't cast away constness like that. In other words, your use of const_cast is illegal.
- eugene.yarovoi July 10, 2012Let me begin by saying this: you're doing something that's not allowed, and it's undefined behavior. We can speculate about the precise technical cause of what you're observing, but at the end of the day, the behavior is compiler-dependent and undefined.
That said, I can try to give a probable explanation of why you're seeing the results you're seeing. The statement cout <<a<<" Address a "<<&a<<endl; is probably being changed to cout <<0<<" Address a "<<&a<<endl; at *compile time*. This is because the compiler automatically does const substitution. After all, the value can't change, so that optimization is safe, right? This is also why you can't arbitrarily cast away constness.
You cannot cast away constness on something that is actually const. This is because, among other reasons, you don't know what performance optimizations may have been performed on occurrences of that variable. The only legitimate use of the const cast is to cast a pointer that is declared a pointer to const *but that you KNOW points to a non-const object or primitive* to a pointer to non-const so that you may then use the non-constness of the object/primitive. Situations where the need to have something like this arises are rare.