C中的大小写可变参数宏 [英] Case variadic macro in C
问题描述
我有2个包装器宏,用于声明函数输入参数:
I have 2 wrapper macros for asserting function input parameters:
/**
* @brief An assert wrapper with no value return in case assert fails.
* @param x_: value to test for being non zero.
*/
#define UTIL_ASSERT_VOID(x_) \
assert_param(x_); \
if (!x_) \
return; \
/**
* @brief An assert wrapper with a value return in case assert fails.
* @param x_: value to test for being non zero.
*/
#define UTIL_ASSERT_VAL(x_, ret_) \
assert_param(x_); \
if (!x_) \
return ret_; \
前者用于返回void的函数,而后者则用于返回non-void的函数.我想知道在C11(或更早版本)中是否存在一种机制,该机制仅允许使用带有可变参数数量的单个宏.根据提供给宏的参数数量(1或2),将编译return
或return ret_
.
The former is used in functions returning void, while the latter in functions returning non-void. I was wondering either in C11 (or earlier) there is a mechanism allowing one to use only a single macro with variadic parameters amount. Depending on how many parameters are provided to the macro (1 or 2), a return
or return ret_
would be compiled.
推荐答案
您可以这样做:
#define UTIL_ASSERT(x_, ...) \
assert_param(x_); \
if (!x_) \
return __VA_ARGS__;
但是请记住,您不能保证在此可变参数宏中仅包含1个参数,因此您需要正确使用它.
But remember, you cannot guarantee just 1 parameter in this variadic macro, so you need to use it correctly.
更新: 多亏了此线程,我才有了更好的方法:
Update: Thanks to this thread, I came to better approach:
void assert_param(int x);
#define UTIL_ASSERT_1(x_) do { assert_param(x_); if (!x_) return; } while(0)
#define UTIL_ASSERT_2(x_, ret_) do { assert_param(x_); if (!x_) return ret_; } while(0)
#define GET_MACRO(_1,_2,NAME,...) NAME
#define UTIL_ASSERT(...) GET_MACRO(__VA_ARGS__, UTIL_ASSERT_2, UTIL_ASSERT_1)(__VA_ARGS__)
int foo() {
UTIL_ASSERT(0,1);
}
void doo() {
UTIL_ASSERT(0);
}
这比以前的要好得多,因为它以某种方式验证了参数的数量.
This one is much better than previous one, because it somehow validates number of parameters.
这篇关于C中的大小写可变参数宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!