Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function-like C macro without parentheses

I have encountered the following debug macro in an embedded device codebase:

extern void DebugPrint(uint8_t *s);

#define DEBUG_MSG(x)   do { PRINT_CURRENT_TIME; \
                            DebugPrint x ; } while(0)

Since there are no parentheses around x in the macro body (at the DebugPrint x part), all calls to this macro (all over the codebase) add another set of parentheses around strings:

DEBUG_MSG(("some debug text"));

Is there any reason to do this? Does it simplify optimizing away these calls in release builds, or something like that? Or is it just plain nonsense?

I thought perhaps there would be additional overloads of DebugPrint with more arguments, but there are none.

like image 826
Lou Avatar asked Sep 08 '15 08:09

Lou


People also ask

How do you define a function-like a macro?

Function-like macro definition: An identifier followed by a parameter list in parentheses and the replacement tokens. The parameters are imbedded in the replacement code. White space cannot separate the identifier (which is the name of the macro) and the left parenthesis of the parameter list.

What is Argumented macro substitution in C?

Macro substitution is a mechanism that provides a string substitution. It can be achieved through "#deifne". It is used to replace the first part with the second part of the macro definition, before the execution of the program. The first object may be a function type or an object.

Can a macro be a function in C?

The Concept of C MacrosMacros can even accept arguments and such macros are known as function-like macros. It can be useful if tokens are concatenated into code to simplify some complex declarations. Macros provide text replacement functionality at pre-processing time.

What is Argumented macro in C?

3.3 Macro ArgumentsTo define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.


1 Answers

Here's a theory:

The preprocessor parses the arguments of a macro expansion in a way that mimics the compiler's expression parsing. In particular it parses terms in parentheses as a single argument.

So the DEBUG_MSG author's intention might have been to enforce the use of parentheses.

This might make sense when the DebugPrint print function would actually be a printf style variadic function. You could call the function with a single string literal or with a variable number of arguments:

DEBUG_MSG(("reached this point in code"));

DEBUG_MSG(("value of x = %i", x));

But this is pure speculation. Can't you just ask the author?

like image 159
Nikolai Ruhe Avatar answered Sep 29 '22 00:09

Nikolai Ruhe