在 C 函数的开头(void)“变量名”是做什么的?

我正在阅读 FUSE 的示例代码:

Http://fuse.sourceforge.net/helloworld.html

我很难理解下面这段代码的作用:

static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
(void) offset;
(void) fi;

具体来说,就是(void)“变量名”的事情。我以前从未在 C 程序中见过这种结构,所以我甚至不知道要在 Google 搜索框中放入什么。我目前最好的猜测是,它是某种未使用的函数参数说明符?如果有人知道这是什么,能帮帮我,那就太好了。谢谢!

47326 次浏览

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.

It does nothing, in terms of code.

It's here to tell the compiler that those variables (in that case parameters) are unused, to prevent the -Wunused warnings.

Another way to do this is to use:

#pragma unused