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
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
If you wish to look at all C Tutorials, go to C Tutorials.
Related Posts:
- Apply for C Internship
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos
- Check C Books
- Check Computer Science Books