Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (void) mean in c++? [duplicate]

Tags:

c++

I'm looking at some code that has a function that looks like this:

void f(A* a, B& b, C* c)
{
   (void)a;
   (void)b;
   (void)c;
}

What exactly does the (void) at the start of every line do?

like image 601
Jesper Evertsson Avatar asked Feb 26 '15 08:02

Jesper Evertsson


3 Answers

What you see there is really just a "trick" to fake variable/parameter usage.

Without those lines, a pedantic compiler will warn you about the variables not being used.

Using a construct (void)variablename; will result in no instructions being generated, but the compiler will consider it a valid "use" of those variables.

like image 56
Mario Avatar answered Nov 13 '22 02:11

Mario


It's simply a kludge to avoid compiler warnings. For example, that code will emit

warning: unused parameter ‘a’ [-Wunused-parameter]
warning: unused parameter ‘b’ [-Wunused-parameter]
warning: unused parameter ‘c’ [-Wunused-parameter]

when compiled with gcc -Wall -Wextra if the kludge is not used. There are cleaner looking ways to achieve this though. You could omit the parameter names:

void f(A*, B&, C*) {
}

A gcc-specifc and somewhat verbose alternative is to use the unused attribute on each unused parameter:

void f(A* a __attribute__((unused)), B& b, C* c) {
}
like image 45
Andy Brown Avatar answered Nov 13 '22 01:11

Andy Brown


I see at least two rerasons. The first one is to avoid warnings of the compiler that the variables are defined but not used in the body of the function.

The second one is that it is very old code and sometimes programmers wrote casting to void before expressions if the result of the expressions is not used. This helped the compiler to optimize generated object code.

like image 2
Vlad from Moscow Avatar answered Nov 13 '22 02:11

Vlad from Moscow