What is ## Preprocessor Directive in C?

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,

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
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.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). 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!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.