Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将数组文字作为宏参数传递_C_C Preprocessor - Fatal编程技术网

C 将数组文字作为宏参数传递

C 将数组文字作为宏参数传递,c,c-preprocessor,C,C Preprocessor,这困扰了我一段时间,例如,如果我试图编写以下代码: // find the length of an array #define ARRAY_LENGTH(arr) (sizeof(arr)/sizeof(int)) // declare an array together with a variable containing the array's length #define ARRAY(name, arr) int name[] = arr; size_t name##_length

这困扰了我一段时间,例如,如果我试图编写以下代码:

// find the length of an array
#define ARRAY_LENGTH(arr) (sizeof(arr)/sizeof(int))   
// declare an array together with a variable containing the array's length
#define ARRAY(name, arr) int name[] = arr; size_t name##_length = ARRAY_LENGTH(name);

int main() {
    ARRAY(myarr, {1, 2, 3});
}
代码给出了以下错误:

<stdin>:8:31: error: macro "ARRAY" passed 4 arguments, but takes just 2
:8:31:错误:宏“ARRAY”传递了4个参数,但只接受2个参数
因为它看到
数组(myarr,{1,2,3})
作为传递
ARRAY
参数
myarr
{1
2
3}
。有没有办法将数组文本传递给宏


编辑:在我需要的一些更复杂的宏中,我可能还需要向宏传递两个或多个数组,因此可变宏不起作用。

是的,
{}
不是预处理器的括号。您可以通过一个伪宏简单地保护参数

#define P99_PROTECT(...) __VA_ARGS__ 
ARRAY(myarr, P99_PROTECT({1, 2, 3}));
在你的情况下应该有用。这样,您就有了一个第一级的
()
,它可以保护
不被解释为参数分隔符。这些宏调用的
()
,然后在展开时消失


请参阅此处,了解更复杂的宏。没有C99 varargs,有什么方法可以做到这一点吗?我想我的意思是减轻一些痛苦,但似乎没有。