What is Nested Directive in C?

This C Tutorial explains Nested Directives in C programming.

Let’s see an example of nested directives to understand them,

/* nested_dir.c-- program illustrate nested directives */
#include <stdio.h>
#define YES
#define NO
 
#undef YES
#undef NO
 
int main(void)
{
    /* let's test if YES and NO are defined or not */
    /* use nested directives */
 
    #ifdef    YES
              #ifdef  NO
                  puts("Both YES and NO defined!");
              #else
                  puts("YES defined!");
              #endif /* NO */
    #elif     NO
                 puts("NO defined!");
    #else
              #error None of YES and NO defined!
    #endif /* YES */
 
    return 0;
}

What’s the output of the above program? This is simple to guess, even. If only YES is defined, massage Yes defined is printed on the terminal, if only NO is defined, massage NO defined is given, if both YES and NO are defined, massage both YES and NO defined is given. Otherwise if none of symbols is defined #error directive gives a text error massage and probably halts the program.

Let’s consider one more example,

/* 
 * nested_dir2.c -- program displays how to manage nested directives
 * in a program
 */
#include <stdio.h>
int main(void)
{
 
    #if    defined(OS_LINUX)
               #ifdef OPTION1
                   os_linux_version_option1();
               #endif /* OPTION1 */
               #ifdef OPTION2
                   os_linux_version_option2();
               #endif /* OPTION2 */
    #elif  defined(MS_DOS)
              #ifdef OPTION2
                   os_ms_dos_version_option2();
           #endif /* MS_DOS */
    #endif
 
    return 0;
}

Above program selects specific OPTION of specific OS.

advertisement
advertisement

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

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

If you find any mistake above, kindly email to [email protected]

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.