Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 656
Lie Ryan Avatar asked Mar 31 '11 16:03

Lie Ryan


1 Answers

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.

like image 182
Jens Gustedt Avatar answered Oct 09 '22 18:10

Jens Gustedt