Home > Net >  Defining a macro as comma (to separate arguemnts with that marco) works properly in functions argume
Defining a macro as comma (to separate arguemnts with that marco) works properly in functions argume

Time:03-30

I come up with a small example of the problem

Assume I have this macro

#define and ,

And I use it like sum(a and b) which should be expanded to sum(a, b).

My problem here is that if sum is defined by a macro the usage example encounters a too few arguments ... error.

Another problem that I think probably will be related and I guess would be solved by the same trick, is when I define an empty macro and place it between function name and argument list. For example

#define of

Now when I use sum of(1, 2), the compiler treats sum as a function and if it is a macro, then, linker throws an undefined reference error.

#define of
#define sum(a, b) a   b

int main()
{
    sum of(a, b); // undefined reference to `sum'
}

CodePudding user response:

Issue with and macro is that a and b is identified as macro argument before replacing and with , happens.

6.10.3.1 Argument substitution

  1. After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## prepro- cessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.

Your second problem is similar but not related. After of is expanded, it is too late to expand sum because it is no longer scanned by the preprocessor:

6.10.3.4 Rescanning and further replacement

  1. After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. The resulting preprocessing token sequence is then rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.
  • Related