sharkin
sharkin

Reputation: 12498

Universally compiler independent way of implementing an UNUSED macro in C/C++

When implementing stubs etc. you want to avoid "unused variable" warnings. I've come across a few alternatives of UNUSED() macros over the years, but never one which either is proven to work for "all" compilers, or one which by standard is air tight.

Or are we stuck with #ifdef blocks for each build platform?

EDIT: Due to a number of answers with non c-compliant alternatives, I'd like to clarify that I'm looking for a definition which is valid for both C and C++, all flavours etc.

Upvotes: 16

Views: 7910

Answers (3)

sharptooth
sharptooth

Reputation: 170479

According to this answer by user GMan the typical way is to cast to void:

#define UNUSED(x) (void)(x)

but if x is marked as volatile that would enforce reading from the variable and thus have a side effect and so the actual way to almost guarantee a no-op and suppress the compiler warning is the following:

// use expression as sub-expression,
// then make type of full expression int, discard result
#define UNUSED(x) (void)(sizeof((x), 0))

Upvotes: 31

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

The universal way is not to turn on warnings options that spam warnings for clearly-correct code. Any "unused variable" warning option that includes function arguments in its analysis is simply wrong and should be left off. Don't litter your code with ugliness to quiet broken compilers.

You might also try sending a bug report to the compiler maintainer/vendor.

Upvotes: -2

tenfour
tenfour

Reputation: 36896

In C++, just comment out the names.

void MyFunction(int /* name_of_arg1 */, float /* name_of_arg2*/)
{
  ...
}

Upvotes: 2

Related Questions