Preprocessor counter macro

Is there a way to create a macro COUNTER()(which follows the C ++ 11/14 standard) that expands to a number that increments each time every time it is called COUNTER()?

I thought about it, but couldn't find a way to make it work. I did not find a way to save the "state" in the macro COUNTER().

Example:

#define COUNTER() <...> // Implementation goes here...
#define UNIQUE_NAME_1() TEST ## COUNTER()
#define UNIQUE_NAME_2() TEST ## COUNTER()

// Note how the COUNTER() macro can be used with other macros
// (it cannot be implemented with C++ code)

int main() {
    std::cout << STRINGIFY(UNIQUE_NAME_1()) << std::endl;
    std::cout << STRINGIFY(UNIQUE_NAME_2()) << std::endl;
}

Expected Result:

TEST0 
TEST1    
+4
source share
1 answer

GCC, and (I believe) VC ++ provide a macro __COUNTER__that does what you expect. I do not know that it exactly matches the standard, but it is probably quite close to the actual use.

+5

Source: https://habr.com/ru/post/1531214/


All Articles