How C Pre-Processor Directive “##” Works?

«
»
This C Tutorial explains how Directive “##” Works.

Like “#” construct “##” construct can be used in the replacement text of function like macro or object like macro. This macro combines two tokens on either side of it into a single token called an identifier. Let’s recall that a token is a group of words separated from its adjacent tokens with white spaces. Also, remember that each token thus created must be a legal identifier. Let’s consider a simple implementation of “##” construct in the following prog.

/* 
 * double_##.c -- program exploits ## capability to create new identifiers
 */
/* ## construct concatenates tokens on either side of it */
#include <stdio.h>
 
#define VAL(n) val ## n
#define PRINTSUM(n,m) \
 printf("sum of val" #n " = %d and val" #m " = %d is %d\n", \
         val ## n, val ## m, val ## n + val ## m)
 
int main(void)
{
    int VAL(1) = 10;  /* becomes val1 = 10 */
    int VAL(2) = 20;  /* becomes val2 = 20 */
 
    PRINTSUM(1,2);
 
    return 0;
}

Observe the output below,

advertisement
sum of val1 = 10 and val2 = 20 is 30

Let’s observe output of above program, just last few lines, generated by preprocessor,
a .i extension file,

advertisement
int main(void)
{
    int val1 = 10;
    int val2 = 20;
 
    printf("sum of val" "1" " = %d and val" "2" " = %d is %d\n",
            val1, val2, val1 + val2);
 
    return 0;
}

Notice that “#” construct creates string and adajecent strings concatenate into one.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn