强制转换为 `void` 到底有什么作用?

What does casting to `void` really do?(强制转换为 `void` 到底有什么作用?)

本文介绍了强制转换为 `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?

推荐答案

强制转换为 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` 到底有什么作用?

基础教程推荐