Well! We all know that while debugging the source code of a program, we generally include printf() statements at several places of doubts to know until where has been execution going correct, until where have been if the values of required variables evaluated correctly? These statements we rather would not physically remove from the source code as the same might be required again while maintenance modifications of the program. In such situations, conditional compilation
is the perfect! Let’s consider a simple ex.,
#include <stdio.h> #define DEBUG printf("value of x = %d and y = %d.\n", x, y) void increase(int, int); int main(void) { int x = 5, y = 6; x++; y++; DEBUG; increase(++x, y++); DEBUG; ++x; ++y; DEBUG; } void increase(int x, int y) { DEBUG; x++; y++; DEBUG; }
Notice that we inserted DEBUG statements at several places to know the modified values of variables x and y to ascertain the way how are they being evaluated in the program? But, of course, we wouldn’t like them to appear in the output once the evaluation trend is clear. we rather hide them by enclosing in conditional directives as follows,
#if 0 DEBUG; #endif
Notice the #if construct which had its matching #endif. This is the simplest conditional compilation construct. Constant exp. zero ‘0’ following #if is considered false and therefore preprocessor deleted the entire #if construct from its output while they are present in the source code.
#if construct also has optional #elif and #else constructs. There can be used any no. of #elif constructs. Let’s consider their syntax first,
#if constan_exp /* statements */ #elif constant-exp /* other statements */ #else /* othet statements */
Notice that constant-exp must be a #defined symbol or literal constant! Variables that don’t attain their values until run time are not legal candidates because their values can’t be determined at the compile time. Let’s see another ex.,
#define MOUSE 10 #define CAT 0 #if MOUSE #include "mouse.h" #elif CAT #include "cat.h" #else #include "horse.h" #endif int main(void) { int x = 10; printf("value of x is %d\n", x); return 0; }
Observe in above program, how conditional compilation directives cause compiler what fragment of code to compile and what to skip. Also, note that any constant exp. is evaluated only if all previous ones are false. If none of the constant exp. is true, and else clause is present, it’s then executed. Preprocessor simply deletes those claues, constant exp. for which is false.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Check Computer Science Books
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for Computer Science Internship