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.


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))

在C ++中,只需将名称注释掉即可。

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

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.

链接地址: http://www.djcxy.com/p/73610.html

上一篇: 将一个“variableName;” C ++语句是一个没有

下一篇: 在C / C ++中实现UNUSED宏的通用编译器独立方式