Nicolás Brailovsky


A modern blog

Unique var name with C/C++ macros

author Posted by: nico on date Jun 25th, 2009 | filed Filed under: C++, Programming
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:
  1. // Do magic! Creates a unique name using the line number
  2. #define LINE_NAME( prefix ) JOIN( prefix, __LINE__ )
  3. #define JOIN( symbol1, symbol2 ) _DO_JOIN( symbol1, symbol2 )
  4. #define _DO_JOIN( symbol1, symbol2 ) symbol1##symbol2

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

     Add A Comment

trackback Trackback URI | rsscomment Comments RSS