Unique var name with C/C++ macros

cpp So, you’re working on some macro magic incantation and you need a unique variable name in you C program? Though it may seem simple at first, using __LINE__ for a variable name, the ## operator (concatenation in the preprocesor) won’t let you. There’s a secret spell to do it anyway:
// Do magic! Creates a unique name using the line number
#define LINE_NAME( prefix ) JOIN( prefix, __LINE__ )
#define JOIN( symbol1, symbol2 ) _DO_JOIN( symbol1, symbol2 )
#define _DO_JOIN( symbol1, symbol2 ) symbol1##symbol2

Great, now you can keep obscuring your programs even more – have fun!

Advertisements

2 Comments on “Unique var name with C/C++ macros”

  1. […] found an interesting little blog post that explains how to generate (semi) unique names in a macro by using the line […]

  2. […] reading this answer to a similar problem, and also attempting this similar concept to create level of indirection, I have found no solution, as neither of them work […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s