Assigning const int to a const pointer to int is illegal?

↘锁芯ラ 提交于 2021-01-28 11:24:07

问题


Why is the following illegal?

extern const int size = 1024;

int * const ptr = &size;

Surely a pointer to non-const data should be allowed to point to a const int (just not the other way around)?

This is from C++ Gotchas item #18


回答1:


If you really meant one of

const int * const ptr = &size; 
const int * ptr = &size;

that is legal. Yours is illegal. Because it it wasn't you could do

int * ptr const = &size;
*ptr = 42;

and bah, your const was just changed.

Let's see the other way around:

int i = 1234; // mutable 
const int * ptr = &i; // allowed: forming more const-qualified pointer
*i = 42; // will not compile

We can't do harm on this path.




回答2:


If a pointer to nonconst data was allowed to point to a const int, then you could use pointer to change the value of the const int, which would be bad. For example:

int const x = 0;
int * const p = &x;

*p = 42;
printf("%d", x);  // would print 42!

Fortunately, the above isn't allowed.



来源:https://stackoverflow.com/questions/17392920/assigning-const-int-to-a-const-pointer-to-int-is-illegal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!