开发者

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

开发者 https://www.devze.com 2022-12-20 02:20 出处:网络
Really simple question about C++ constness. So I was reading this post, then I tried out this code: int some_num = 5;

Really simple question about C++ constness.

So I was reading this post, then I tried out this code:

int some_num = 5;
con开发者_如何学编程st 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


I agree with Jared Par's answer. Also, check out the C++ FAQ on const correctness.


The const keyword just tells the compiler that you want some stricter checking on your variable. Castring a non const integer to a const integer pointer is valid, and just 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, writing

*some_num_ptr = 6;

should give an error since the pointer points to a const int.

Writing

some_num = 7;

remains valid of course.


int* ptr; just says you can't change the valued pointed to by ptr through ptr. The actual value might still be changed by other means.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号