考虑下面的代码,它来自这个问题 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?