Is GCC warning on const qualifier correct?

跟風遠走 提交于 2019-12-22 06:42:20

问题


Consider the follow code, which arose from this question:

const int (*foo(const char *a))[1]
    { return (const int (*)[1]) a; }

When compiled with GCC 8.2 (and older versions) using -Wcast-qual, GCC warns:

source>:2:15: warning: cast discards 'const' qualifier from pointer target type [-Wcast-qual]
      { return (const int (*)[1]) a; }
               ^

Is this warning correct? Clearly the destination type has a const qualifier in it.

It is on the element type rather than on the thing immediately pointed to by the pointer, which is the array type. However, the warning remains even if we use typedef int T[1]; and replace the cast with (const T *). Additionally, per C 2018 6.7.3 10, qualifiers on an array type apply to the element type, not the array type, so the type is the same either way.

Clang does not show this warning.

If we change the cast to (const void *):

const int (*foo(const char *a))[1]
    { return (const void *) a; }

then the warning vanishes. If we add -pedantic to the compilation switches, we get a different warning about const:

source>:2:15: warning: return discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
      { return (const void *) a; }
               ^~~~~~~~~~~~~~~~

This looks like the same warning except it is about the implied conversion from the return expression to the function return type, whereas the previous warning was about the explicit conversion in the cast. But this one appears only with -pedantic. Why?


回答1:


This is GCC bug 81631. GCC fails to recognize the cast to a pointer to an array retains the const qualifier, due to complications with qualifiers applied to an array actually applying to the array elements.



来源:https://stackoverflow.com/questions/54507856/is-gcc-warning-on-const-qualifier-correct

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