How can I construct a locally unique identifier name?

c++, c-preprocessor, uniqueidentifier, visual-c++, visual-studio-2010

Solution

For a unique identifier, many implementations offer the `__COUNTER__` preprocessor macro, that expands to an ever increasing number with every use.

#define CAT(a,b) CAT2(a,b) // force expand
#define CAT2(a,b) a##b // actually concatenate
#define UNIQUE_ID() CAT(_uid_,__COUNTER__)

auto UNIQUE_ID() = call(1); // may be _uid_0
auto UNIQUE_ID() = call(2); // may be _uid_1

Problem

I want to create a unique variable name on the fly. This is my code: ``` int call(int i) { return i; } #define XCAT3(a, b, c) a ## b ## c #define CALL_2(arg, place, line) int XCAT3(cl, place, line) = call(arg); #define CALL_1(arg) CALL_2(arg, __FUNCTION__, __LINE__) int main(int argc, char* argv[]) { CALL_1(1); /* this is line 20 */ return 0; } ``` This does work in GCC (http://ideone.com/p4BKQ) but unfortunately not in Visual Studio 2010 or 2012. The error message is: test.cpp(20): error C2143: syntax error : missing ';' before 'function_string' test.cpp(20): error C2143: syntax error : missing ';' before 'constant' test.cpp(20): error C2106: '=' : left operand must be l-value How can I create an on-the-fly unique variable name with C++? Solution: ``` #define CAT2(a,b) a##b #define CAT(a,b) CAT2(a,b) #define UNIQUE_ID CAT(_uid_,__COUNTER__) int main(int argc, char* argv[]) { int UNIQUE_ID = 1; int UNIQUE_ID = 2; return 0; } ```

Original source

Related problems