3

is it possible to call macro inside a macro in this way:

#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 followinf error in the compilation:

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 identifier is reported only once for each function it appears in

4
  • are you really missing the ending }? Commented Jul 8, 2015 at 13:11
  • What happens when you try it? Commented Jul 8, 2015 at 13:13
  • Omit the semicolon after the macro, or - better - if using gcc, parenthesise the whole macro body (non-standard) to make that an expression. Commented Jul 8, 2015 at 13:15
  • The problem is in your error. You've defined BB with 5 parameters, and only supplied 2 when you call it. Commented Jul 8, 2015 at 13:19

2 Answers 2

6

What you probably want is to supply additional arguments of BB by expansion of AA(n,k). As pointed by Sourav Ghosh, in your program, AA(n,k) is expanded after being passed to BB as a single argument. To get it expanded before, you can use one more 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));
}
Sign up to request clarification or add additional context in comments.

Comments

4

In your code, when the following line is encountered, in preprocessing stage,

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

as per the rule of MACRO substitution, first, BB will get expanded (replaced) as specified in the replacement-list, then, in the replacement list, if any other MACRO substitution is possible (here, AA), that will take place next.

There the problem arises. MACRO definition of BB takes 5 arguments, but you're passing only 2, because, the expansion of AA did not take place yet.

Related, from C11, chapter §6.10.3, Macro replacement (emphasis mine)

A preprocessing directive of the form

  # define identifier replacement-list new-line

defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive. The replacement list is then rescanned for more macro names as specified below.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.