What does casting to `void` really do?(强制转换为 `void` 到底有什么作用?)
问题描述
像(void)x;
这样的常用语句允许抑制关于未使用变量x
的警告.但是,如果我尝试编译以下内容,则会得到一些我不太明白的结果:
An often used statement like (void)x;
allows to suppress warnings about unused variable x
. But if I try compiling the following, I get some results I don't quite understand:
int main()
{
int x;
(short)x;
(void)x;
(int)x;
}
使用 g++ 编译它,我收到以下警告:
Compiling this with g++, I get the following warnings:
$ 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)
或其他类型相同.我对可能的解释的猜测是:
So I conclude that casting to void
is very different from casting to any other types, be the target type the same as decltype(x)
or something different. My guess at possible explanations is:
- 这只是一个约定,
(void)x;
而不是其他强制转换会抑制警告.所有的陈述同样没有任何影响. - 这种差异在某种程度上与
void x;
不是有效语句而short x;
是这样的事实有关.
- It is just a convention that
(void)x;
but not the other casts will suppress warnings. All the statements equally don't have any effect. - This difference is somehow related to the fact that
void x;
isn't a valid statement whileshort x;
is.
以下哪个更正确?如果没有,那么如何解释编译器警告的差异?
Which of these if any is more correct? If none, then how can the difference in compiler warnings be explained?
推荐答案
强制转换为 void 用于抑制编译器警告.标准在§5.2.9/4中说,
Casting to void is used to suppress compiler warnings. The Standard says in §5.2.9/4 says,
任何表达式都可以显式转换为cv void"类型.这表达式值被丢弃.
Any expression can be explicitly converted to type "cv void." The expression value is discarded.
这篇关于强制转换为 `void` 到底有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制转换为 `void` 到底有什么作用?


- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01