Macro Concatenation in C

Recently, I came across a question on C programming . The question seemed odd at first, but later on further research, revealed a lot of information, which I had not known earlier.


#define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}

The output would be


100

How you ask? Here’s my explanation.

The ## (double hash sign) operator concatenates two tokens in a macro invocation.

Consider this :


#define f(g,g2) g##g2

The given function call is f(var,12). Here, when the macro is invoked, g would be assigned var and g2 would be assigned 12.

The ## operator concatenates var and 12 to form var12.

Now, consider the printf statement :


printf("%d",f(var,12));

The value returned after the macro has been invoked would be var12, and the printf statement will now be,


printf("%d",var12);

which in turn would print 100 as the answer, since the integer variable var12 has been assigned the value 100.

Advertisements

About Manikandan Surendren

A PeopleSoft Techno-functional Consultant. An engineering graduate in Computer Science. Technology Enthusiast. Movie freak. Gadget geek.
This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s