Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ const : how come the compiler doesn't give a warning/error

Tags:

c++

constants

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.

like image 944
sivabudh Avatar asked Dec 06 '22 03:12

sivabudh


1 Answers

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

like image 110
JaredPar Avatar answered Feb 16 '23 18:02

JaredPar