Monday, January 19, 2009

Preprocessor Operators - # and ##

Have you ever heard of the preprocessor operators "Stringize" (denoted as #) and "Token Pasting" (denoted as ##)?

If you know this already well and good but shame.. I learnt abt this only today and hence sharing.... Oh well, It's better late than never :)


The operator # indicates that the following argument is to be replaced by a string literal; this literal names the preprocessing token that replaces the argument. For example, consider the macro:

#define display(x) show((long)(x), #x)

When the preprocessor reads the line


it replaces it with the following:

show((long)(abs(-5)), "abs(-5)");

"Token Pasting" or "Token concatenation"

The ## operator performs ``token pasting'' - that is, it joins two tokens together, to create a single token. For example, consider the macro:

#define printvar(x) printf("%d\n", variable ## x)

When the preprocessor reads the line


it translates it into:

printf("%d\n", variable3);

PS: In the past, token pasting had been performed by inserting a comment between the tokens to be pasted. This no longer works.