强制转换为“ void”到底有什么用? [英] What does casting to `void` really do?

查看:196
本文介绍了强制转换为“ 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 while short x; is.

其中有哪些(如有)更正确吗?如果没有,那么如何解释编译器警告中的差异呢?

Which of these if any is more correct? If none, then how can the difference in compiler warnings be explained?

推荐答案

使用无效铸造用于禁止编译器警告。 §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”到底有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆