Double pointer const-correctness warnings in C

隐身守侯 提交于 2019-11-26 01:45:40

The reason why const can only be added one level deep is subtle, and is explained by Question 11.10 in the comp.lang.c FAQ.

Briefly, consider this example closely related to yours:

const int i;
int *p;
int const **z = &p;
*z = &i;
/* Now p points to i */

C avoids this problem by only allowing assignment to discard qualifiers at the first pointed-to level (so the assignment to z here is not allowed).

Your exact example does not suffer from this problem, because the const the second level means that the assignment to *z would not be allowed anyway. C++ would allow it in this exact case, but C's simpler rules do not distinguish between your case and the example above.

The FAQ entry linked by the other answer explains why the following code is not permitted:

int **x = whatever;
const int **z = x;

However, your code const int *const *z = x; is quite different, and it does not suffer from the same flaw raised by the FAQ.

In fact, there is conceptually nothing wrong with the latter code. It is just a flaw in the C specification that it is not permitted, and it forces C programmers to include ugly casts in their code.

It would have been possible for C to use the same rules that C++ did; however the C standard committee didn't decide to do that.

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