(void)var 实际上是做什么的? [英] What does (void)var actually do?

查看:63
本文介绍了(void)var 实际上是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的main():

int main(int argc, char *argv[])
{
    return (0);
}

使用 cc -Wall -Wextra 编译后,会生成警告说未使用的参数".

Upon compilation with cc -Wall -Wextra, warnings saying "unused parameter" get generated.

当我不需要在函数中使用参数时(例如在 信号处理函数中 不使用其 int 参数),我习惯于执行以下操作:

When I do not need to use a parameter in a function (for instance in a signal handler function that makes no use of its int parameter), I am used to doing the following:

  int main(int argc, char *argv[])
  {
      (void)argc;
      (void)argv;
      return (0);
  }

(对于那个特定的 main(),我有时会看到其他人这样做:argv = argv - argc + argc)

(For that particular main(), I sometimes see other people do: argv = argv - argc + argc)

但是(void)var实际上做什么?

But what does (void)var actually do?

我知道 (void) 是一个强制转换,所以我想我正在抛弃变量?var; 行(不带演员表)有什么作用?是一个空的赋值,一个空的表达式吗?

I understand that (void) is a cast, so I guess I am casting away the variable? What does the var; line (without the cast) do? Is it an empty assignment, an empty expression?

我想了解实际情况.

推荐答案

这只是创建对变量的无害"引用的一种方式.编译器不会抱怨未使用的变量,因为您确实引用了该值,并且它不会抱怨您没有对表达式 var 的值执行任何操作,因为您显式地强制转换它to void (nothing),表示你不关心值.

It's just a way of creating a 'harmless' reference to the variable. The compiler doesn't complain about an unused variable, because you did reference the value, and it doesn't complain that you didn't do anything with the value of the expression var because you explicitly cast it to void (nothing), indicating that you didn't care about the value.

我以前从未在变量上看到过这种用法(因为我使用的编译器通常不会抱怨未使用的函数参数,)但我看到这经常用于向编译器表明您并不真正关心函数的返回值.printf(), 例如,返回一个值,但 99% 的 C 程序员不知道(或关心)它返回什么.为了让一些繁琐的编译器或 lint 工具不会抱怨未使用的返回值,您可以将返回值强制转换为 void,以表明您知道它在那里,并且您明确不关心它.

I haven't seen this usage on variables before (because the compiler I use doesn't normally complain about unused function arguments,) but I see this used frequently to indicate to the compiler that you don't really care about the return value of a function. printf(), for example, returns a value, but 99% of C programmers don't know (or care) what it returns. To make some fussy compilers or lint tools not complain about an unused return value, you can cast the return value to void, to indicate that you know it's there, and you explicitly don't care about it.

除了将您的意图(您不关心这个值)传达给编译器之外,它实际上没有任何事情——它只是对编译器的一个提示.

Other than communicating your intent (that you don't care about this value) to the compiler, it doesn't actually do anything - it's just a hint to the compiler.

这篇关于(void)var 实际上是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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