GCC 对 const 限定符的警告是否正确?

2024-01-02

考虑下面的代码,它来自这个问题 https://stackoverflow.com/questions/54502385/gcc-casting-const-pointers-to-const-pointer-of-array-typedef-with-wcast-qual-t?noredirect=1#54502385>:

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

When 使用 GCC 8.2(及更早版本)编译-Wcast-qual https://godbolt.org/z/e6_Wfi,海湾合作委员会警告:



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

这个警告正确吗?显然,目标类型有一个const其中的限定符。

它是在元素类型上,而不是在指针直接指向的东西上,即数组类型。但是,即使我们使用,警告仍然存在typedef int T[1];并将演员阵容替换为(const T *)。此外,根据 C 2018 6.7.3 10,数组类型的限定符适用于元素类型,而不是数组类型,因此无论哪种方式,类型都是相同的。

Clang 不显示此警告。

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

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

然后警告消失。如果我们添加-pedantic对于编译开关,我们收到不同的警告const:



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

这看起来像是相同的警告,只不过它是关于从返回表达式到函数返回类型的隐式转换,而之前的警告是关于强制转换中的显式转换。但这个只出现在-pedantic. Why?


This is 海湾合作委员会错误 81631 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81631。由于应用于数组的限定符实际应用于数组元素的复杂性,GCC 无法识别对数组指针的转换保留了 const 限定符。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GCC 对 const 限定符的警告是否正确? 的相关文章

随机推荐