C provides a very useful and interesting feature called “conditional Compilation”
the general structure for doing it:
here if macroname has been #defined then the 4 statements will be compiled otherwise not.
There are 3 scenarios where I see application of this feature:
-> To “comment out” obselete lines of code. It may happen that a program undergoes a change for some reasons.
Here we may not want to delete the old code but add new code.
In this scenario, we can include the old and new code in ifdef block and control the compilation using a single #define statement.
here , if we define thee macro “OLD” then old code is compiled otherwise, the new code is compiled.
->The other (more sophisticated) use of this feature can be to make the programs more portable.
Thus, we can make use of this feature and make a program work on two completely different computers.
code for intel PC
code for motorola PC
code common for both.
This code is pretty self explanatory.
If you want your code to run on INTEL we just need to define a macro.
->A third possible scenario is defining of custom functions.
Lets say we define a function called “my_sample_function()” in a file “file1.h”
Also, “file1.h” is included in “file2.h”
If we include both the files, compiler will throw an error saying “multiple declaration of my_sample_function()”
To overcome this problem, we can use the following way:
/* file1.h */
/*some code */
Here when file1.h gets included first time, compiler knows that macro _file is not defined. Thus it gets defined and the rest of code is compiled.
Next time, since the macro stands defines, the function does not get compiled and thus there is no error.
NOTE: #ifndef is exactly opposite of #ifdef
Conditional compilation can also be achieved using #if ,#else #endif statements.
#if is used to evaluate whether a expression evaluated to nonzero value or not.
it is used in the same way as above: