(void)var 是在干嘛

最近在看 muduo 的代码,看到类似这样的写法:

size_t n = activeTimers_.erase(timer);
assert(n == 1); (void)n;

而且不止一处,于是就很好奇,这种 (void)var 是在干嘛,查了一下,这里说道,http://stackoverflow.com/quest…

It works around some compiler warnings. Some compilers will warn if you don’t use a function parameter. In such a case, you might have deliberately not used that parameter, not be able to change the interface for some reason, but still want to shut up the warning. That (void) casting construct is a no-op that makes the warning go away. Here’s a simple example using clang:

int f1(int a, int b)
{
(void)b;
return a;
}

int f2(int a, int b)
{
return a;
}
Build using the -Wunused-parameter flag and presto:

$ clang -Wunused-parameter -c -o example.o example.c
example.c:7:19: warning: unused parameter ‘b’ [-Wunused-parameter]
int f2(int a, int b)
^
1 warning generated.

让人不得不感慨,cpp 的世界里欢乐多啊。。

One thought on “(void)var 是在干嘛

  1. 这也不是 C++ 特有问题嘛,想方设法绕过静态分析检查的总是有的…… Python 里有有人写 foo = foo 来绕过 lint 工具的 unused variable 警告。

Leave a Reply

Your email address will not be published. Required fields are marked *