syntax highlight

Thursday, 25 June 2009

Unique var name with C/C++ macros

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!

2 comments:

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

    ReplyDelete
  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 […]

    ReplyDelete