Why one needs two brackets to use macros in c/c++?

2020-07-23 02:11发布

问题:

    KdPrint(("Enter HelloWDMAddDevice\n"));

What's the reason for doing that?

回答1:

That is so you can pass an entire argument list to the macro and have it pass it on to a function that takes a variable number of arguments.

I would bet anything that the definition of that macro is:

#if DEBUG /* or something like it */
#define KdPrint(args) (printf args)
#else
#define KdPrint(args) /* empty */
#endif

Or similar to some other function that works just like printf.

If it were defined as printf(args), then you could only pass the single string argument, because an argument to a macro can't contain a comma that isn't inside a nested parenthesis.



回答2:

If the macro in question was not well written using parentheses, it might be necessary because of operator precedence. Take this macro for example:

#define MY_MACRO(a) a * 11

Well, if you did this:

int b = MY_MACRO(1 + 2);

b, instead of being 33 like it should, would actually be replaced with int b = 1 + 2 * 11 which is 23 and not 33. If your macro isn't written like that, though (without parenthesis around the a) then it's unnecessary.



回答3:

It causes everything inside the parens to be treated as a single parameter to the macro. In the example shown, it can allow for varargs types of parameters:

KdPrint(( "My info is %s\n", "my name" ));

As well as

KdPrint(( "fn %s ln %s\n", "my", "name" ));


回答4:

If this is the KdPrint() that you are talking about, then this is because you can use KdPrint() macro with format arguments, and it is not a variable length macro.

For example, you can do:

KdPrint(("The answer is %d\n", 42));

and so on.



回答5:

For your specific example, I cannot tell you, because I don't know what is XdPrint.

But in a more general case, it is because a macro I just like a search and replace. Suppose you have:

#define MULT(a,b) (a*b)

If you call MULT(1+1, 2+2), it would become 1+1*2+2, and result as 5 instead of 8 as you would expect. Doing MULT((1+1), (2+2)) would gives you the expected result. That is why you need to double the brackets.



标签: c macros