C语言 (void)“变量名”在 C 函数的开头有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7354786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:36:29  来源:igfitidea点击:

What does (void) 'variable name' do at the beginning of a C function?

cfuse

提问by fyhuang

I am reading this sample code from FUSE:

我正在从 FUSE 阅读此示例代码:

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

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

And I am having trouble understanding what the following snippet of code does:

我无法理解以下代码片段的作用:

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;

Specifically, the (void) "variable name" thing. I have never seen this kind of construct in a C program before, so I don't even know what to put into the Google search box. My current best guess is that it is some kind of specifier for unused function parameters? If anyone knows what this is and could help me out, that would be great. Thanks!

具体来说,(无效)“变量名”的东西。我以前从未在 C 程序中看到过这种构造,所以我什至不知道该在 Google 搜索框中输入什么内容。我目前最好的猜测是它是未使用的函数参数的某种说明符?如果有人知道这是什么并且可以帮助我,那就太好了。谢谢!

回答by Carl Norum

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:

它可以解决一些编译器警告。如果您不使用函数参数,某些编译器会发出警告。在这种情况下,您可能故意不使用该参数,由于某种原因无法更改界面,但仍想关闭警告。该(void)铸造构造是一个无操作,使警告消失。这是一个使用 clang 的简单示例:

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

int f2(int a, int b)
{
  return a;
}

Build using the -Wunused-parameterflag and presto:

使用-Wunused-parameterflag 和 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.

回答by Macmade

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 -Wunusedwarnings.

在这里告诉编译器这些变量(在那种情况下是参数)未使用,以防止出现-Wunused警告。

Another way to do this is to use:

另一种方法是使用:

#pragma unused