sanjoyd
sanjoyd

Reputation: 3340

Weird use of void

I've been going through some C source code and I noticed the following:

void some_func (char *foo, struct bar *baz)
{
    (void)foo;
    (void)baz;
}

Why is void used here? I know (void) before an expression explicitly indicates that the value is thrown away; but can someone please explain me the rationale for such an use?

Upvotes: 11

Views: 644

Answers (3)

paxdiablo
paxdiablo

Reputation: 882028

The most likely reason for those variables to appear at all in the function is to remove any warnings about unused arguments.

However, since this is likely to introduce yet another warning (since you're probably using a higher-than-normal warning level), the author goes an extra step to remove those as well.

In C, the statement

42;

is actually valid, though not very useful. If you compile:

int main (void) {
    42;
    return 0;
}

it will not complain (normally). However, if you compile that with gcc -Wall -pedantic (for example), you'll get something like:

prog.c: In function `main':
prog.c:2: warning: statement with no effect

because the compiler, rightly so, thinks you've gone crazy.

Putting a (void) cast before something that generates a value, like the 42; will explicitly state that you don't care about the value.

I've seen this used on some anal-retentive compilers which insist that, because a function like printf actually returns a value, you must be mad for ignoring it, leading to such atrocities as:

(void)printf ("Hello, world.\n");
(void)strcpy (dest, src);

:-)


By way of example, if you compile:

void some_func (char *foo) {}
int main (void) { some_func (0); return 0; }

with gcc -Wall -W -pedantic, you'll get:

warning: unused parameter `foo'

If you "use" the parameter:

void some_func (char *foo) { foo; }

you'll get

warning: statement with no effect

However, if you use the parameter and explicitly ignore the result:

void some_func (char *foo) { (void)foo; }

you'll get no warnings at all.

Upvotes: 6

blucz
blucz

Reputation: 1666

Most likely, someone was building this code with a compiler that emits warnings for unused arguments, and wanted to suppress the warnings.

Upvotes: 8

Eugene Smith
Eugene Smith

Reputation: 9398

This code ensures that you won't get a compiler warning about foo and baz being unused.

Upvotes: 22

Related Questions