I need to use parentheses in my actual parameters for a macro, but the parentheses appear to be changing the behavior of the comma separating the macro parameters.
I had my preprocessor dump its output into a text file, so I could see what it was producing.
Then I performed a basic test to confirm the behavior.
#define MACRO_TEST_1( X , Y ) X && Y
MACRO_TEST_1 ( A , B )
// Desired result: A && B
// Actual result: A && B
MACRO_TEST_1 ( ( C , D ) )
// Desired result: ( C && D )
// Actual result: ( C , D ) &&
// Warning: "not enough actual parameters for macro 'MACRO_TEST_1'"
It appears that adding an opening parenthese to the first parameter, and a closing parenthese to the second parameter, causes the preprocessor to treat the comma as part of the first parameter, and therefore assumes that I did not supply a second parameter at all.
This is evidenced by the warning, as well as the preprocessor output showing nothing after the &&.
So my question is, how can I tell the preprocessor that the comma seperates the parameters, even though the parameters have parentheses in them?
I tried escaping the parentheses or the comma, but this made no difference.
(Same results, just with the escape character inserted into the preprocessor output.)
I technically found a solution, albeit ugly.
You have to define symbols for the parentheses characters.
#define OP (
#define CP )
#define MACRO_TEST_1( X , Y ) X && Y
MACRO_TEST_1 ( A , B )
// Desired result: A && B
// Actual result: A && B
MACRO_TEST_1 ( OP C , D CP )
// Desired result: ( C && D )
// Actual result: ( C && D )
So my question is, how can I tell the preprocessor that the comma separates the parameters, even though the parameters have parentheses in them?
I think that there is no way, at least in such macro implementation.
From the gcc.gnu.org:
To invoke a macro that takes arguments, you write the name of the macro followed by a list of actual arguments in parentheses, separated by commas.
Leading and trailing whitespace in each argument is dropped, and all whitespace between the tokens of an argument is reduced to a single space. Parentheses within each argument must balance; a comma within such parentheses does not end the argument.
You cannot leave out arguments entirely; if a macro takes two arguments, there must be exactly one comma at the top level of its argument list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With