Really simple question about C++ constness.
So I was reading this post, then I tried out this code:
int some_num = 5;
const int* some_num_ptr = &some_num;
How come the compiler doesn't give an error or at least a warning?
The way I read the statement above, it says:
Create a pointer that points to a constant integer
But some_num is not a constant integer--it's just an int.
The problem is in how you're reading the code. It should actually read
Create a pointer to an integer where the value cannot be modified via the pointer
A const int*
in C++ makes no guarantees that the int
is constant. It is simply a tool to make it harder to modify the original value via the pointer
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