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;
}