像 (void)x;
这样经常使用的语句允许抑制关于未使用变量 x
的警告。但是如果我尝试编译以下内容,我会得到一些我不太明白的结果:
int main()
{
int x;
(short)x;
(void)x;
(int)x;
}
使用 g++ 编译,我收到以下警告:
$ g++ test.cpp -Wall -Wextra -o test
test.cpp: In function ‘int main()’:
test.cpp:4:13: warning: statement has no effect [-Wunused-value]
(short)x;
^
test.cpp:6:11: warning: statement has no effect [-Wunused-value]
(int)x;
^
所以我得出结论,转换为 void
与转换为任何其他类型非常不同,目标类型与 decltype(x)
相同或不同。我对可能的解释的猜测是:
- 这只是
(void)x;
而不是其他强制转换会抑制警告的约定。所有的陈述同样没有任何效果。 - 这种差异在某种程度上与
void x;
不是有效语句而short x;
是。
如果有的话,哪一个更正确?如果没有,那么如何解释编译器警告的差异?
最佳答案
强制转换为 void 用于抑制编译器警告。 Standard在 §5.2.9/4 中说,
Any expression can be explicitly converted to type “cv void.” The expression value is discarded.
关于c++ - 转换到 `void` 的真正作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34288844/