'Create an identifier at compile time that has the line number as part of it [duplicate]

I want a C++ preprocessor macro that creates a new identifier with the line number as part of it. This is for using the identifier as a throwaway variable that doesn't collide with any other variable name. For e.g., if I write

VARNAME("Var")

at line number 100 of a file, I want the preprocessor to generate the variable name:

Var100

How do I do this please? I know I have to use stringification and the __LINE__ predefined macro, but I cannot quite figure out how to put it all together.



Solution 1:[1]

You may use the following:

#define CAT_(a, b) a ## b
#define CAT(a, b) CAT_(a, b)
#define VARNAME(Var) CAT(Var, __LINE__)

Example

Run this full Demo here::

#define CAT_(a, b) a ## b
#define CAT(a, b) CAT_(a, b)
#define VARNAME(Var) CAT(Var, __LINE__)

int main()
{
    int VARNAME(i) = 0;  // produces `int i7 = 0;` since this is on line 7
}

Output

Notice that the variable name generated by int VARNAME(i) is i7, as shown in the error output:

echo clang=============;clang++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
echo gcc  =============;g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
clang=============
main.cpp:7:9: warning: unused variable 'i7' [-Wunused-variable]
    int VARNAME(i) = 0;
        ^
main.cpp:3:22: note: expanded from macro 'VARNAME'
#define VARNAME(Var) CAT(Var, __LINE__)
                     ^
main.cpp:2:19: note: expanded from macro 'CAT'
#define CAT(a, b) CAT_(a, b)
                  ^
main.cpp:1:20: note: expanded from macro 'CAT_'
#define CAT_(a, b) a ## b
                   ^
<scratch space>:3:1: note: expanded from here
i7
^
1 warning generated.
gcc =============
main.cpp: In function 'int main()':
main.cpp:7:17: warning: unused variable 'i7' [-Wunused-variable]
     int VARNAME(i) = 0;
                 ^
main.cpp:1:20: note: in definition of macro 'CAT_'
 #define CAT_(a, b) a ## b
                    ^
main.cpp:3:22: note: in expansion of macro 'CAT'
 #define VARNAME(Var) CAT(Var, __LINE__)
                      ^
main.cpp:7:9: note: in expansion of macro 'VARNAME'
     int VARNAME(i) = 0;
         ^

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriel Staples