Home > Net >  How to retrieve a previously declared variable with __COUNTER__ pasted inside its name in C ?
How to retrieve a previously declared variable with __COUNTER__ pasted inside its name in C ?

Time:05-09

I have the following problem:

#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)

If I wanted to retrieve a specific variable##__COUNTER__ later in the code how can I achieve this? I only need to get the previous one, something like:

#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N, VAL) CONCAT(N, VAL)

auto CREATE_NAME(v);
auto test_current_counter_value = GET_NAME_PREV(v, __COUNTER__ -1);

Thank you.

CodePudding user response:

BOOST_PP_SUB macro from boost library can be evaluated and expanded to an identifier.

#include <boost/preprocessor/arithmetic/sub.hpp>

#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N) CONCAT(N, BOOST_PP_SUB(__COUNTER__, 1))

auto CREATE_NAME(v) = true;
auto test_current_counter_value = GET_NAME_PREV(v);

Try it on Compiler Explorer.

  • Related