What does (void)var actually do?

半城伤御伤魂 提交于 2019-11-28 08:24:08

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.

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)argc;
  (void)argv;

If a function argument is not used, like in your program, then this is the idiomatic way of suppressing the warning of unused function argument issued by some compilers. Any decent compiler will not generate code with these statements.

It evaluates the argument but does nothing with it which has the effect for most compilers to not issue a warning. The (void) cast is used so the compiler would not produce another warning notifying that the value is not used.

Another popular way to suppress the warning is to do:

variable = variable;

Note that I know some compilers that will issue another warning in presence of:

(void) arg;

like "statement with no effect".

As other persons correctly noted, It just suppresses a compiler warning about unused variable in your code. Btw, Win32 has defined UNREFERENCED_PARAMETER macro to reach this goal. My suggestion to make something like that in your code:

#ifdef _WIN32
# define UNUSED(x) UNREFERENCED_PARAMETER(x)
#else
# define UNUSED(x) (void) x
#endif

This may increase the code efficiency because the call of function dont need to load the registers for arguments.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!