gpt4 book ai didi

c - GCC 关于 const 限定符的警告是否正确?

转载 作者:太空狗 更新时间:2023-10-29 15:03:19 29 4
gpt4 key购买 nike

考虑以下代码,这些代码来自 this question :

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

compiled with GCC 8.2 (and older versions) using -Wcast-qual , GCC 警告:

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

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

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

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

最佳答案

这是 GCC bug 81631 . GCC 无法识别指向数组指针的转换保留了 const 限定符,因为应用于数组的限定符实际上应用于数组元素。

关于c - GCC 关于 const 限定符的警告是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507856/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com