考虑下面的代码,它源自
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
,海湾合作委员会警告:
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
对于编译开关,我们得到一个不同的警告
康斯特
:
source>:2:15: warning: return discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
{ return (const void *) a; }
^~~~~~~~~~~~~~~~
这看起来像是相同的警告,只是关于从返回表达式到函数返回类型的隐式转换,而前面的警告是关于强制转换中的显式转换。但这一个只出现在
学究式的
. 为什么?