#if allows you to
define more generalized conditions. Multiple conditions, which are connected by
relational operators such as AND(&&), OR(||), are allowed.The else
directive lets us specify the action if the #if condition is not true.
Program
Suppose
we have three files:
file1.h
#define USD 1
file2.h
#define UKP 1
file3
#include <stdio.h>
#include <file1.h> //A
#if (defined (USD)) // B
#define currency_rate 46
#else
#define currency_rate 100
//C
#endif //D
main()
{
int rs;
rs = 10 *
currency_rate; //H
printf
("%d\n", rs);
}
Explanation
- Statement B indicates the ifelse directive.
- If the identifier USD is defined, the currency
rate is taken as 46; otherwise, the currency rate is taken as 100.
- Since USD is defined in file1.h, the currency rate is taken
as 46.
Point to Remember
The ifelse directive allows us to take action if the
condition is not satisfied.
ifelif allows us to take one action if
there are multiple decision points. For example, if you want to take the
currency rate of 1 if USD and UKP are not defined, you can write the following
program.
Program
file1.h
#define USD 1
file2.h
#define UKP 1
file3
#include <stdio.h>
#include <file1.h> //A
#if (defined (USD)) // B
#define
currency_rate 46
#elif (defined (UKP))
#define
currency_rate 100 //C
#else
# define
currency_rate 1 //D
#endif
main()
{
int rs;
rs = 10 *
currency_rate; //H
printf
("%d\n", rs);
}
Explanation
- Statement B includes the ifelif directive. It is similar to
the else directive.
- #elif appears only after #if, #ifdef, #ifndef, and #elif.
- #elif is similar to #else but it is followed by a
condition.
- You can have as many #elif directives as you want.
- If USD is defined, then the
currency rate is 46; otherwise, if UKP is defined, then the currency rate
is 100; otherwise, the currency rate is 1.
- In this case, if you remove
the statement include
file1.h at
position A, then USD and UKP are not defined and currency rate is taken as
1.
Points to Remember
- #elif is
similar to #else but it is followed by a
condition.
- #elif allows taking action in the
case of multiple decision points.
The error
directive is used to specify an error message for a specific situation. In
the following program, the error message is displayed if USD and UKP are not defined.
Program
Suppose
we have three files:
file1.h
#define USD 1
file2.h
#define UKP 1
file3
#include <stdio.h>
#include <file1.h> //A
#if !defined (USD) || !defined (UKP) // B
#error "ERROR: NO_CURRENCY rate is specified."
//C
#endif
main()
{
int rs;
rs = 10 *
currency_rate; //D
printf
("%d\n", rs);
}
Explanation
- Statement B checks whether UKP or USD is defined.
- If both are not defined then
the preprocessor displays an error.
Points to Remember
- The #error directive allows us to
specify an error message.
- The error message is
generated by the preprocessor.