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` 到底有什么作用?
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01