在C / C实现未使用的宏通用编译器无关的方法++ [英] Universally compiler independent way of implementing an UNUSED macro in C/C++

查看:168
本文介绍了在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?

编辑:由于一些非C标准的替代答案,我想澄清,我正在寻找一个定义,它是有效的C和C ++中,所有的味道等等。

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.

推荐答案

据<一个href=\"http://stackoverflow.com/questions/4030959/will-a-variablename-c-statement-be-a-no-op-at-all-times/4030983#4030983\">this由用户回答 GMAN 中的的典型的办法是转换为无效

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

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

但如果 X 标记为挥发性,将执行从变量读取,从而有一个副作用,所以几乎保证无操作和SUP preSS的编译器警告实际的方法如下:

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 / C实现未使用的宏通用编译器无关的方法++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆