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

拥有回忆 提交于 2019-11-27 01:52:56

问题


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.


回答1:


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



回答2:


In C++, just comment out the names.

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



回答3:


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.



来源:https://stackoverflow.com/questions/4851075/universally-compiler-independent-way-of-implementing-an-unused-macro-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!