Typecast to (void)

B

Billy Mays

Periodically I see code that looks similar to this:


void do_something(int a, int b)
{
(void) b;
printf("A is %d\n", a);
}

What does this typecast do? Running code like this through lint
complains the "(void) b" statement does nothing. Any thoughts?
 
K

Keith Thompson

Billy Mays said:
Periodically I see code that looks similar to this:

void do_something(int a, int b)
{
(void) b;
printf("A is %d\n", a);
}

What does this typecast do? Running code like this through lint
complains the "(void) b" statement does nothing. Any thoughts?

It's probably intended to silence a warning about b not being
used in the function. Whether it actually does so depends on the
compiler or other tool being used. Some compilers might issue a
warning if b isn't referred to at all, but shut up if it appears as
"(void) b;". For whatever version of lint you're using, as you've
seen, it doesn't work particularly well.

(Lints typically recognize directives in the form of C comments that
tell them to inhibit certain warnings. I say "lints" rather than
"lint" because there are multiple versions of lint, just as there
are multiple distinct C compilers.)
 
N

Nick

Kenneth Brody said:
It's purpose is to "do nothing", just like lint says.

Well, to be more precise, it's to "use" the otherwise-unused parameter
"b", but not do anything with it.

And the reasons you might want to do this are

1) that you intend to add 'b' later (or have eliminated 'b' and don't
want to change all your header files etc). This isn't a very good
reason and the second version is particularly weak.

2) that this is one of a pile of functions with a similar prototype that
is called from a function pointer - perhaps from a table. This is much
more reasonable.

The problem is that many compilers will complain about:
void do_something(int a, int b)
{
printf("A is %d\n", a);
}
and some of them can be silenced by adding the
(void) b;

Some can't. Many compilers have a non-standard way to do this properly:
gcc has an __attribute__((unused)) that can be used for the purpose.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top