Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 256
sharkin Avatar asked Jan 31 '11 12:01

sharkin


1 Answers

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))
like image 155
sharptooth Avatar answered Sep 21 '22 14:09

sharptooth