6

Is there a way to create a COUNTER() macro (which follows the C++11/14 standard) that is expanded to a number which increases by one every time COUNTER() is invoked?

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

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 output:

TEST0 
TEST1    
0

1 Answer 1

7

GCC, and (I believe) VC++ both provide the __COUNTER__ macro, which does about what you'd expect. I don't know that it follows the standard exactly, but it's probably close enough for real-world use.

Sign up to request clarification or add additional context in comments.

1 Comment

stackoverflow.com/questions/652815/… has some nice coverage on this topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.