How do I call a macro inside a macro?

Is it possible to call a macro inside a macro like this:

#include <stdio.h>
#define AA(a1, a2) a1, 3, 5, a2
#define BB(x, y1, y2, y3, y4) { printf("%d %d %d %d %d\n",x, y1, y2, y3, y4 ); }

int main ()
{
   int n = 21, k= 11;
   BB(31, AA(n,k));
}

      

this code returns the following compilation error:

test_macro.c: In function 'main:
test_macro.c: 9: 18: erreur: macro "BB" requiert 5 arguments, mais seulement 2 ont été passés
test_macro.c: 9: 4: erreur: "BB undeclared (first use in this function)
test_macro.c: 9: 4: note: each undeclared id is reported only once for every function that appears in

+3


source to share


2 answers


You probably need to provide additional arguments BB

by extension AA(n,k)

. As pointed out by Sourav Ghosh, your program AA(n,k)

expands after being passed in BB

as one argument. To expand on it, you can use another macro level and define your program as:



#define AA(a1, a2) a1, 3, 5, a2
#define BB(x, y1, y2, y3, y4) { printf("%d %d %d %d %d\n",x, y1, y2, y3, y4 ); }
#define BBB(a,b) BB(a,b)

int main ()
{
  int n = 21, k= 11;
  BBB(31, AA(n,k));
}

      

+5


source


In your code, when the next line is encountered, in the preprocessing step

BB(31, AA(n,k));

      

according to the substitution rule MACRO, firstly, it BB

will expand (replace) as indicated in the substitution list, and then in the substitution list, if any other MACRO substitution is possible (here AA

), which will go further.



The problem arises. The MACRO definition BB

takes 5 arguments, but you only pass 2 because the expansion AA

hasn't taken place yet.

Related, from C11

, chapter §6.10.3, macro replacement (emphasis mine)

Form preprocessing directive

  # define identifier replacement-list new-line

      

defines an object-like macro that replaces each subsequent instance of the macro name with a replacement list of preprocessing tokens that make up the remainder of the directive. The list is then replaced with rescanning for more macro names as indicated below.

+3


source







All Articles