Introduction
The ifdef directive makes substitutions based on whether a particular identifier is defined.
Program
Suppose we have three files:
file1.h #define USD 1 file2.h #define UKP 1 file3 #include#include //A #ifdef USD // B #define currency_rate 46 //C #endif //D #ifdef UKP // E #define currency_rate 100 //F #endif //G main() { int rs; rs = 10 * currency_rate; //H printf ("%d\n", rs); }
Explanation
-
Statement A includes file1.h, so the content of the file is substituted in that position. If the file name is given in angle brackets, it means the file is searched in the default search path. If the file name is specified within “”, like include "file1.h", then file1.h is searched only in the current directory.
-
Statement B is an ifdef directive and it checks whether the identifier USD is defined. Since it is defined in file1.h, the condition is true and the currency rate is defined as 46. You can include multiple directives in if, def and endif.
-
Statement E checks whether the identifier UKP is defined. Since it is not defined, because file2.h, is not included in the file, the condition is false and its defined directive is not processed.
-
The currency rate in file3 is taken as 46.
-
In the expression in statement H, the currency rate is substituted as 46.
-
If, instead of file1.h, you include file2.h, then the currency rate will be 100.
Points to Remember
-
ifdef is used to make a substitution depending on whether a certain identifier is defined.
-
If the identifier is defined, it returns true; otherwise, it is false.
No comments:
Post a Comment