Passing array literal as macro argument

2019-02-04 21:27发布

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条回答
Melony?
2楼-- · 2019-02-04 22:11

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.

查看更多
登录 后发表回答