What does (void) 'variable name' do at the beginning of a C function? [duplicate]
Asked Answered
O

2

87

I am reading this sample code from FUSE:

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!

Oldest answered 8/9, 2011 at 21:34 Comment(1)
Came here while reading fuse code : DTailgate
C
129

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.
Credendum answered 8/9, 2011 at 21:36 Comment(6)
Wouldn't it be more semantic to use #define IGNORE_UNUSED(var) (void)(var) then?Errancy
@nightcracker, I don't know what "more semantic" means, but the OP's usage is a pretty common idiom.Credendum
@Carl Norum: Ah, if it's a common idiom than there is no point in using that macro for it.Errancy
It's the same as the UNREFERENCED_PARAMETER macroPediform
@orlp, the difference is that using the macro you disable that warning for the whole compilation unit (in this case, everywhere the macro is defined). Using (void) you disable the warning for that specific function and that specific parameter, only.Levirate
C23 has introduced an attribute [[maybe_unused]] which let you get rid of the warning in a more readable way.Prong
I
12

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
Intellect answered 8/9, 2011 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.