开发者

Passing array literal as macro argument

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: 开发者_Python百科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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜