我想要一个可以转换此内容的 C 预处理器宏:
if (IN(node->type, BRANCH, CAPTURE_START, CAPTURE_END)) {
...
}
对此:
if (node->type == BRANCH || node->type == CAPTURE_START || node->type == CAPTURE_END) {
...
}
这有点类似于 MySQL IN 运算符。可能吗?
最佳答案
CPP 不支持迭代参数列表。 “C”中最接近的结构将是 switch 语句,但它不会导致自身
switch (node->type ) {
case V1:
case V2:
case V3:
...
}
作为替代方案,您可以获得更符合“IN”测试的内容,使用 带有 vararg 函数的函数。这是限制:(1) 类型必须已知,(2) 将有一个特殊值(示例中的 LAST)来指示列表的末尾
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#define LAST (-1)
bool in_int_set(int v, ...)
{
va_list ap ;
va_start(ap, v) ;
for (;;) { // forever
int s = va_arg(ap, int) ;
if ( s == LAST ) return false ;
if ( s == v ) return true ;
} ;
}
void main(void) {
printf("A=%d\n", in_int_set(5, 3, 5, 7, LAST)) ;
printf("B=%d\n", in_int_set(5, 2, 4, 6, 8, 10, LAST)) ;
// From the question about
if ( in_int_set(node->type, BRANCH, CAPTURE_START, CAPTURE_END, LAST) ) {
...
}
}
关于c - 有没有办法编写一个带有变量参数的 C 预处理器宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58195228/