Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

constants - Double pointer const-correctness warnings in C

A pointer to non-const data can be implicitly converted to a pointer to const data of the same type:

int       *x = NULL;
int const *y = x;

Adding additional const qualifiers to match the additional indirection should logically work the same way:

int       *      *x = NULL;
int       *const *y = x; /* okay */
int const *const *z = y; /* warning */

Compiling this with GCC or Clang with the -Wall flag, however, results in the following warning:

test.c:4:23: warning: initializing 'int const *const *' with an expression of type
      'int *const *' discards qualifiers in nested pointer types
    int const *const *z = y; /* warning */
                      ^   ~

Why does adding an additional const qualifier "discard qualifiers in nested pointer types"?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...