Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

fuse

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!

like image 858
fyhuang Avatar asked Sep 08 '11 21:09

fyhuang


People also ask

What is a void variable in C?

The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

What is the significance of void * in C?

In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal.

Can we declare a variable as void in C?

The "void" is used as a data type but we can not use it for variable declaration in 'C'. In c void means the variable we contains null value, which is not possible.

What does temporary void mean?

It means that the value of temp is otherwise unused, and the optimizing compiler warns about it (variable is set but not used), but by including the (void)temp; , you (currently) get away without the warning from the compiler.


1 Answers

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. 
like image 143
Carl Norum Avatar answered Sep 30 '22 23:09

Carl Norum