sramij
sramij

Reputation: 4925

Using brackets in a macro definition

I would like to define a macro, such as:

  #define EX(X)   (myArray # X + otherArray # X)

so when I write:

   v = EX([a+1][a+2]);

This will evaluate into:

   v = myArray[a+1][a+2] + otherArray[a+1][a+2];

But this doesn't work, and somehow adds extra parenthesis too.

Upvotes: 1

Views: 1371

Answers (1)

bgoldst
bgoldst

Reputation: 35314

# is the stringification operator. Your desired output has no strings, so you don't need it.

You may have been going for the ## token pasting operator, but that doesn't make sense for your intended functionality, since the [ character cannot form part of a valid preprocessing token. In any case, you don't need it, because you can simply expand the X parameter adjacent to the myArray/otherArray identifiers with whitespace separation (see below).

In a function-like macro definition, everything following the whitespace after the parameter list is the "body" of the function-like macro, and thus becomes part of the expansion. This means any parentheses you include in the body will be part of the expansion (unless they form part of a function-like macro call, which they don't in your case). If you don't want them in the expansion, don't include them in the body.

You can achieve your desired output with this:

#define EX(X) myArray X + otherArray X

This expands to

v = myArray [a+1][a+2] + otherArray [a+1][a+2];

If you really care about the space between the array identifier and the subscripts (there's no reason why you should), you can get rid of them with the following trick:

#define EXPAND(...) __VA_ARGS__
#define EX(X) EXPAND(myArray)X + EXPAND(otherArray)X

The above expands to

v = myArray[a+1][a+2] + otherArray[a+1][a+2];

Upvotes: 7

Related Questions