开发者

How to get the last value of __COUNTER__

I have a macro that does something similar to the following:

#define MAKE_VALS(...开发者_如何转开发) \
    int val1 = 0; \
    int val2 = 0; \
    :
    if(val1 == val2) \
    { \
        ... 
    }

and I need to use it multiple times within a single function. The trouble is, using it multiple times causes multiple definition errors due to multiple definitions of val1 and val2.

Using __COUNTER__ with ## would solve the problem, but I can't see how to get the correct variable names for the if statement? I can't use __COUNTER__ again because I'd get the next value. I need a way to get the last value of __COUNTER__. Can it be done?

PS. I don't want to surround it with {}s to fix the problem. I've simplified the real problem here and using {}s causes other problems (that aren't important to what I'm asking).


For whatever the purpose of this is, you can achieve that using several levels of macros:

#define MAKE_VALS(...) MAKE_VALS1(..., __COUNTER__)
#define MAKE_VALS1(..., counter) MAKE_VALS2(..., counter)
#define MAKE_VALS2(..., counter) \
   int val1##counter = 1; int val2##counter = 2; \
   val1##counter = whatever; val2##counter = hunoz;

This way, you can use MAKE_VALS more than once in the same scope, and every call will create a new set of variables. Note that without MAKE_VALS1, your variables would be named val1__COUNTER__ and so on, and the extra level makes it the actual number.

It's a nice exercise in macro writing, but I agree with the guys before me who questioned if this is the right way to achieve whatever you're trying to achieve. But enough has been said about that, so I hope this solves your problem.


#define MAKE_VALS(m, n, ...) \
    int val ## m = 0; \
    int val ## n = 0; \
    :
    if(val ## m == val ## n) \
    { \
        ... 
    }

Use:

 MAKE_VALS(__LINE__,
           __LINE__, ... ); //second __LINE__ on next line

Put second __LINE__ on next line to avoid having same value for both m and n.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜