Sometimes in your macros you need to use a variable, but you can’t scope it to the macro. If you use this macro more than one in the same scope you get a duplicate variable warning.

For example, let’s say this is your macro:

#define LOOP_10_TIMES \
int i = 0; \
for( i = 0; i < 10; ++i)

And this is your implementation:

LOOP_10_TIMES{
	x += i;
}

This is fine, but what happens when you want to use this macro twice? Like so:

LOOP_10_TIMES
	num += i;

LOOP_10_TIMES
	mun += i;

You’re sure to get a nasty error (or at least a warning).
This is because your code now declares the variable ‘i’ twice in the same scope.

So how do we solve this? Our macro needs to create its own unique variable each time and use that instead. This is where the __LINE__ preprocessor directive comes into play

Using __Line__ you can figure out what on what line in the file the call to the macro is located. So if you combine the current line with the name of your variable you can create a unique variable which will never repeat within the same source file twice.

So how do you generate a unique variable? Use this handy code:

#define _LINENAME_CONCAT( _name_, _line_ ) _name_##_line_
#define _LINENAME(_name_, _line_) _LINENAME_CONCAT(_name_,_line_)
#define _UNIQUE_VAR(_name_) _LINENAME(_name_,__LINE__)

You’re probably wondering why this code does in 3 nested calls what it can do with just one… well if you consolidate these three lines into one it just won’t work.. try it out. This works though, I promise.

Ok so now that the hard part is over, here’s how you use it

So here’s a little usage example:


//Note the line that the code is actually on

int _UNIQUE_VAR(myVar) = 5;
int _UNIQUE_VAR(myVar) = 10;
int _UNIQUE_VAR(myVar) = 20;

//This is what the output is

print( myVar3 ); //output: 5
print( myVar4 ); //output: 10
print( myVar5 ); //output: 20

I hope that helps you, it took a while to figure out but it’s definitely useful in a sticky macro situation