传递数组文本作为宏参数 [英] Passing array literal as macro argument

查看:290
本文介绍了传递数组文本作为宏参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已被窃听我一段时间,例如,如果我试图写这个code:

This has been bugging me for some time, for example, if I'm trying to write this code:

// 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});
}

在code给出了这样的错误:

The code gives this error:

<stdin>:8:31: error: macro "ARRAY" passed 4 arguments, but takes just 2

由于它看到阵列(myArr,该{1,2,3}); 作为传递 ARRAY 参数 myArr,该 {1 2 3} 。有没有办法通过一个的数组文本的宏?

Because it sees ARRAY(myarr, {1, 2, 3}); as passing ARRAY the argument myarr, {1, 2, and 3}. Is there any way to pass an array literal to macros?

编辑:在一些较复杂的宏我需要的,我也可能需要两个或更多阵列传递给宏,所以可变参数宏不起作用

In some of the more complex macros I needed, I may also need to pass two or more arrays to the macro, so variadic macro does not work.

推荐答案

是的, {} 不是为preprocessor括号。你可以简单地通过一个虚拟的宏保护参数

Yes, the {} aren't parenthesis for the preprocessor. You can simply protect the arguments by a dummy macro

#define P99_PROTECT(...) __VA_ARGS__ 
ARRAY(myarr, P99_PROTECT({1, 2, 3}));

应该在你的情况下工作。由您的第一级(),保护被间preTED作为参数分隔符。这些()宏调用,那么在扩张中消失。

Should work in your case. By that you have a first level of () that protects the , from being interpreted as argument separator. These () of the macro call then disappear on the expansion.

在这里看到更多复杂的宏,用以完成声明unroling

See here for more sophisticated macros that do statement unroling.

这篇关于传递数组文本作为宏参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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