codeLover
codeLover

Reputation: 3810

Different syntax for #define in C/C++ including many statements

I understand the syntax of #define like,

#define Pi 3.14

So it's obvious that we can use Pi constant instead of 3.14 anywhere in code to make code more readable.

But I encountered a syntax like below.

Does it mean whenever I call the macro

doIT("hello world");

the code statements within {...} will be invoked ?

Does #define allow to give such syntax.? What does the __FUNCTION__, __VA_ARGS__ mean ?

#define doIT(str, ...)                                                                      \
{                                                                                               \
    if (pDoLog) pDoLog->LogMsg("[%s] Error: " str, LOG_WRONG, __FUNCTION__, ##__VA_ARGS__); \
    printf("[%s] Error: " str "\n", __FUNCTION__, ##__VA_ARGS__);                               \
}

Upvotes: 1

Views: 151

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171433

You don't "call" a macro, and its expansion doesn't get "invoked". The preprocessor just replaces the macro with its expansion, before the code gets compiled.

A macro defined with parentheses such as doIt(str) is a "function-like macro" which means it takes arguments which can be used in the expansion of the macro.

A function-like macro with ... in the argument list indicates it can accept a variable number of arguments. The special predefined symbol __VA_ARGS__ expands to the list of arguments passed to the ... placeholder.

__FUNCTION__ is a special predefined symbol that expands to the name of the current function being compiled, so wherever the macro gets expanded it will use the name of the enclosing function.

Upvotes: 4

Related Questions