Keil Logo

GENERAL: C MACRO EXPANSION PROBLEM WITH PARAMETERS


Information in this article applies to:

  • C51 All Versions
  • C166 All Versions
  • C251 All Versions
  • CARM All Versions

QUESTION

I have a problem with macro expansion and a parameter list in the following source code.

#define           CONCAT(A,B) A##B
#define           RES(R)            R
#define           MSO               1

CONCAT ( TR_,RES(MSO) );   // should give TR_1, but results in TR_RES(1)
CONCAT ( RES(MSO),_TR );   // should give 1_TR, and works OK

The parameters of a C macro are replaced if they are macros itself. Why doesn't this work?

ANSWER

In general, you are correct: macro parameters are replaced if they are macros. However, the ## operator implies a different behavior and inserts a placeholder which is replaced later.

To get the result that you expect, you must add another macro and rewrite your macros as follows:

#define  CONCAT(a, b) XCAT(a, b)
#define  XCAT(a, b)   a ## b
#define  RES(R)       R
#define  MSO          1


CONCAT ( TR_,RES(MSO) );      // gives now TR_1
CONCAT ( RES(MSO),_TR );      // gives 1_TR as before

MORE INFORMATION

  • ANSI C Reference Manual

SEE ALSO

Last Reviewed: Monday, June 6, 2005


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.