C ++ const: why the compiler does not give a warning / error

Really simple question about C ++ constant.

So, I read this post , then I tried this code:

int some_num = 5; const int* some_num_ptr = &some_num; 

Why does the compiler not give an error, or at least a warning?

As I read the above statement, he says:

 Create a pointer that points to a constant integer 

But some_num is not a constant integer - it's just an int.

+4
source share
4 answers

The problem is how you read the code. He must really read

Create a pointer to an integer where the value cannot be changed with a pointer

A const int* in C ++ does not guarantee that the constant is int . This is just a tool that makes it difficult to change the original value with a pointer

+12
source

I agree with Jared Par's answer. Also, check out the C ++ Frequently Asked Questions for const correctness .

+2
source

The const keyword tells the compiler that you want to test your variable more strictly. Casting a non const integer to a const integer pointer is valid and simply tells the compiler that it should give an error if you try to change the value of the contents of the const pointer.

In other words, the record

 *some_num_ptr = 6; 

should give an error, because the pointer points to const int.

Record

 some_num = 7; 

remains valid, of course.

+2
source

int* ptr; just says that you cannot change the value pointed to by ptr through ptr . Actual value may be changed in other ways.

(the actual reason the compiler doesn't warn is because casts from T * to const T * are implicit)

0
source

Source: https://habr.com/ru/post/1301033/


All Articles