Thread: Using Macro as a argument

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    1

    Post Using Macro as a argument

    I want to use a macro (say MACRO1) used as a argument to other macro (say MACRO2). I know that this works when MACRO1 is defined for a value as shown below.

    #define MACRO1 5000
    #define MACRO2 MACRO1*MACRO1

    But in my case, MACRO1 is a variable name i.e.

    #define MACRO1 my_var
    And I want to create a other variable which has ‘_count’ appended in name defined for MACRO1 like

    #define MACRO2 MACRO1 # _count
    But above line is not getting preprocessed as expected. It is returning ‘MACRO1_count’ where as I need ‘my_var_count’.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I'm pretty sure it's just a typo, but ## is for token pasting/concatenation. A single # is for stringizing.

    The preprocessor is just a fancy text replacement system. But the text replacement doesn't happen in the #define, it happens where MACRO1 or MACRO2 are used. It works for stuff like multiplication because when MACRO2 is expanded to MACRO1*MACRO1, it's left with two MACRO1 tokens. The preprocessor knows MACRO1 is 5000 and can thus replace it. In the case of the token pasting operator though, when you use MACRO2, it is expanded to MACRO1_count. MACRO1_count is not something that the preprocessor recognizes, so it doesn't know how to expand it.

    You can look into using something like X-Macros, which might help. As a fall back, you can try something like m4 macros if you really really need this. Othewise, I think you're out of luck.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Argument inside the Argument of a Function Declaration
    By manasij7479 in forum C++ Programming
    Replies: 3
    Last Post: 06-11-2011, 05:53 AM
  2. macro
    By siperi in forum C Programming
    Replies: 1
    Last Post: 11-15-2010, 04:32 AM
  3. MACRO-need help
    By new-b in forum C Programming
    Replies: 13
    Last Post: 06-22-2009, 10:17 PM
  4. Is this a macro?
    By Morgan in forum C Programming
    Replies: 1
    Last Post: 01-23-2003, 01:49 PM
  5. macro
    By sballew in forum C Programming
    Replies: 2
    Last Post: 10-10-2001, 07:51 PM

Tags for this Thread