Passing array literal as macro argument

浪子不回头ぞ 提交于 2019-12-18 12:18:49

问题


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

The code gives this error:

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

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?

EDIT: 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.


回答1:


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

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.

See here for more sophisticated macros that do statement unroling.



来源:https://stackoverflow.com/questions/5503362/passing-array-literal-as-macro-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!