GCC对const限定词的警告正确吗? [英] Is GCC warning on const qualifier correct?

查看:483
本文介绍了GCC对const限定词的警告正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码,该代码源自

Consider the follow code, which arose from this question:

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

使用-Wcast-qual 与GCC 8.2(和较旧版本)编译时,GCC警告:


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

此警告是否正确?显然,目标类型中包含const限定符.

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

它是在元素类型上,而不是在指针立即指向的东西上,它是数组类型.但是,即使使用typedef int T[1];并用(const T *)替换强制类型转换,警告仍然存在.此外,根据C 2018 6.7.3 10,数组类型上的限定符适用于元素类型,而不适用于数组类型,因此两种类型的类型相同.

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不显示此警告.

Clang does not show this warning.

如果我们将演员表更改为(const void *):

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

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

然后警告消失.如果将-pedantic添加到编译开关,则会收到有关const的不同警告:

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; }
               ^~~~~~~~~~~~~~~~

除了警告有关从return表达式到函数return类型的隐式转换,这看起来像是相同的警告,而先前的警告与强制转换中的显式转换有关.但是,这个仅出现在-pedantic上.为什么?

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?

推荐答案

这是 GCC错误81631 .由于将限定符应用于实际应用于数组元素的数组的复杂性,GCC无法识别出对指向数组的指针的转换,从而保留了const限定符.

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.

这篇关于GCC对const限定词的警告正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆