c++ - 转换到 `void` 的真正作用是什么?

标签 c++ casting compiler-warnings void suppress-warnings

(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/

相关文章:

c++ - 将标记从词法分析器传递到解析器

C++ 转换会创建一个新对象吗?

vb.net - 在 VB.NET 中进行转换

c# - 在 C# 中定义泛型类型的显式转换

c++ - 在 C++ 中迭代 .bmp 的像素

c++ - 有条件地传递修改后的拷贝而不是 const original 变得丑陋

c++ - 警告 : zero as null pointer constant while comparing iterators

c - 警告:函数的隐式声明

c++ - 使用 stdin stdout 和 stderr 启动 exe/进程?

java - Android Studio 中的原始类型警告