While I was learning about const variables in c++, I tried this :
#include <iostream>
int main()
{
const int p = 20;
int* a = const_cast<int*>(&p);
*a = 10;
std::cout<<"Value at a: "<<(*a)<<std::endl;
std::cout<<"Value of p: "<<p<<std::endl;
std::cout<<"Their addresses : "<<std::endl;
std::cout<<a<<" "<<&p<<std::endl;
return 0;
}
and it produces the output:
Value at a: 10
Value of p: 20
Their addresses :
0x7fff4646d7d4 0x7fff4646d7d4
Seemingly I assigned the value 10 to the memory address of p, but their values come out different. Why is it so?
C++ Constant Pointers to constants: In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.
We declare a pointer to constant. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of 'ptr'.
int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.
int const *ptr; We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case).
Attempting to modify an object that was originally declared const
gives you undefined behaviour.
§7.1.6.1/4 [dcl.type.cv] Except that any class member declared
mutable
can be modified, any attempt to modify aconst
object during its lifetime results in undefined behavior.
Chances are, your compiler is replacing all occurences of p
in your code with the value 20
, since you have promised that it will not change. So the line that prints p
has changed to:
std::cout<<"Value of p: "<<20<<std::endl;
So it prints 20
regardless of whether you modified the original object. Of course, since you have undefined behaviour, this kind of reasoning is fruitless and you should not invoke undefined behaviour in your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With