C++ anonymous variables

情到浓时终转凉″ 提交于 2019-12-12 08:13:30

问题


Why won't this work?

 0. #define CONCAT(x, y) x ## y
 1. 
 2. #define VAR_LINE(x) \
 3.     int CONCAT(_anonymous, __LINE__) = x
 4. 
 5. #define VAR_LINE2(x) \
 6.     int _anonymous ## x = 1
 7.
 8. int main()
 9. {
10.     VAR_LINE(1);
11.     VAR_LINE(1);
12.     VAR_LINE(1);
13.     VAR_LINE2(__LINE__);
14. }

The result from the above macro expansion

int _anonymous__LINE__ = 1;
int _anonymous__LINE__ = 1;
int _anonymous__LINE__ = 1;
int _anonymous13 = 1;

It would be convenient if I didn't have to write that __LINE__ macro as an argument.

I'm thinking the problem is pretty clear. I want to be able to generate anonymous variables so that this macro doesn't fail with redefinition error when declaring several variables within the same scope. My idea was to use the predefined __LINE__ macro because no variable will ever be declared on the same line like this. But the macro expansion troubles me, can you help?

Update: Correct answer

Thanks to Luc Touraille. However, there was a tiny problem with the suggested solution. There has to be whitespace between the operands and the ## operator (apparently the standard says otherwise but the the PS3 flavoured GCC would not expand the macro properly if there were no whitespace between the operator and operands).

#define _CONCAT(x,y) x ## y
#define CONCAT(x,y) _CONCAT(x,y)

The VAR_LINE macro now yields:

int _anonymous10 = 1;
int _anonymous11 = 1;
int _anonymous12 = 1;

This has been verified to work under Win32 (Visual Studio 2008), XBOX360 (Xenon) and PS3.


回答1:


You need to add a level of indirection so that __LINE__ will be expanded:

#define _CONCAT_(x,y) x ## y
#define CONCAT(x,y) _CONCAT_(x,y)

#define VAR_LINE(x) int CONCAT(_anonymous, __LINE__) = x


来源:https://stackoverflow.com/questions/461062/c-anonymous-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!