"Dynamic" creation of variables through macros

Hi,
I wanted to know if something like this is possible:

#define CREATEVAR(X) X##__LINE__

but expanding the __LINE__ macro.

I'm trying to create a variable's name through a macro that could be called different times creating different names:
int CREATEVAR(a);
int CREATEVAR(a);

(of course, in this case it would only work if the macro was called in different lines).

The thing is that after the concatenation operator ## the macros don't get expanded, so, I'd like to know if there's any way around this.

Thank you.



Answer this question

"Dynamic" creation of variables through macros

  • isha_2

    Hi -

    I found this code at http://msdn2.microsoft.com/en-us/library/b0084kay.aspx, in the section describing __COUNTER__

    -----------------------------

    // pre_mac_counter.cpp
    #include <stdio.h>
    #define FUNC2(x,y) x##y
    #define FUNC1(x,y) FUNC2(x,y)
    #define FUNC(x) FUNC1(x,__COUNTER__)
    
    int FUNC(my_unique_prefix);
    int FUNC(my_unique_prefix);
    
    int main() {
      my_unique_prefix0 = 0;
      printf_s("\n%d",my_unique_prefix0);
      my_unique_prefix0++;
      printf_s("\n%d",my_unique_prefix0);
    }

    ---------------------------

    The three FUNC macros do what you want.

    In this code, the first "int FUNC(my_unique_prefix);" global variable becomes "int my_unique_prefix0;", and the second one becomes "my_unique_prefix1" (that's the way the __COUNTER__ predefined macro works...it just keeps incrementing)

    I tried it with __LINE__ instead of __COUNTER__, and it works there, too. I don't know how you plan on using a variable whose name is variable, though...

    Good luck,

    Brad


  • DragonSpeed

    Thank you,
    I forgot to mention that I needed it to be ansi and __COUNTER__ is VS specific.


    EDIT:

    I did it just replacing the __COUNTER__ with __LINE__.

    #define FUNC2(x,y) x##y
    #define FUNC1(x,y) FUNC2(x,y)
    #define FUNC(x) FUNC1(x,__LINE__)

    Can someone tell me why we need to encapsulate things this way (with various macros)  so we can do this kind of concatenation


  • "Dynamic" creation of variables through macros