Why is a level of indirection needed for this concatenation macro?

admin

Administrator
Staff member
I found <a href="http://monoinfinito.wordpress.com/2009/06/25/unique-var-name-with-cc-macros/" rel="noreferrer">an interesting little blog post</a> that explains how to generate (semi) unique names in a macro by using the line number:

Code:
// 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

There are two things here that really confuse me:

<ol>
<li>Why does the
Code:
LINE_NAME
macro even work if
Code:
JOIN
is declared after it in the file? I thought the C preprocessor did a linear pass, and thus would need the macros to be defined based on dependency, just like C functions need to be defined before they're used.</li>
<li>Why is it necessary to use both the
Code:
JOIN
and
Code:
_DO_JOIN
macros in order to get the correct result? Having this level of indirection in the macros seems very strange.</li>
</ol>

I have a feeling that the answers to both those questions are related, and have to do with the way that the C preprocessor evaluates macros. (However, my intuition on how macros work is apparently way off since I didn't even think that the example was valid.)