How to use #if #elif #else #endif in Macro
Description
Logical directive tests whether an identifier exists as a result of
having been created in a previous #define
directive.
Syntax
C Conditional Compilation takes the following form:
#if defined identifier
...
#endif
If identifier
is defined,
statements between #if
and #endif
are included in the program
code.
If the identifier isn't defined, the statements between the
#if
and the #endif
will be skipped.
Absence of an identifier
Test for the absence of an identifier. In fact, this tends to be used more frequently than the form you've just seen.
The general form of this directive is:
#if !defined identifier
Here, the statements following the #if
down to the
#endif
will be included if the identifier
hasn't previously been defined.
Multiple conditions
To define more generalized conditions.
Multiple conditions are connected by relational operators such as AND(&&), OR(||).
#define USA 1// w w w . j a v a 2 s . c o m
#include <stdio.h>
#if ((1>0) && defined USA)
#define currency_rate 46
#endif
#if (defined (EUP))
#define currency_rate 100
#endif
main()
{
int rs;
rs = 10 * currency_rate;
printf ("%d\n", rs);
}
The code above generates the following result.
#elif and #else
#ifelif allows us to take one action for multiple decision entries.
#define USA 1/* w w w. j av a 2s. co m*/
#define EUP 1
#include <stdio.h>
#if (defined (USA))
#define currency_rate 46
#elif (defined (EUP))
#define currency_rate 100
#else
#define currency_rate 1
#endif
main()
{
int rs;
rs = 10 * currency_rate;
printf ("%d\n", rs);
}
The code above generates the following result.
If undefined
#ifndef
is used to check whether a particular symbol is defined.
#define USA 1/*from w ww . j a v a 2 s. co m*/
//#define EUP 1
#include <stdio.h>
#ifndef USA
#define currency_rate 100
#endif
#ifndef EUP
#define currency_rate 46
#endif
main()
{
int rs;
rs = 10 * currency_rate;
printf ("%d\n", rs);
}
The code above generates the following result.
#ifdef
The #ifdef
directive makes substitutions based on
whether a particular identifier is defined.
#define USA 1//from ww w .j a va 2 s. c o m
// #define EUP 1
#include <stdio.h>
#ifdef USA
#define currency_rate 46
#endif
#ifdef EUP
#define currency_rate 100
#endif
main()
{
int rs;
rs = 10 * currency_rate;
printf ("%d\n", rs);
}
The code above generates the following result.