This blog is under construction

Sunday, 12 January 2014

#if, #elif, #else and #endif example

#if
If the resultant value of the arithmetic expression is non-zero, then the code between #if and #endif will be compiled.

Example:
#if 10 > 5
     printf("10 is greater than 5");
#endif

The code between #if and #endif will be compiled since the resultant value of the expression(10 > 5) is non-zero.


#elif
This provides an alternate expression to evaluate

Example:
#if 10 < 5
     printf("10 is less than 5");
#elif 10 > 5
     printf("10 is greater than 5");
#endif

The expression at #if directive evaluates to 0.  So, the expression at #elif is evaluated. If it is non-zero, then the code between #elif and #endif will be compiled.


#else
If the resultant value of the arithmetic expression is false for #if, #ifdef or #ifndef, then the code between #else and #endif will be compiled.

Example:
#if 10 < 5
     printf("10 is less than 5");
#else
     printf("10 is greater than 5");
#endif


#endif
This acts as an end directive for #if, #ifdef, #ifndef, #elif or #if

#if 100 < 50   // resultant value of expression is 0
   printf("#if directive");
#elif 50 < 10  // resultant value of the expression is 0
    printf("#elif directive");
#else
    printf("#else directive");  // this statement would be executed
#endif

Example C program to illustrate #if #elif #else #endif usage in C:

  #include <stdio.h>
  #define VAL1 10
  #define VAL2 20
  #define VAL3 30

  int main() {
    #if VAL1 > VAL2
          printf("%d is greater than %d\n", VAL1, VAL2);
    #elif VAL1 > VAL3
          printf("%d is greater than %d\n", VAL1, VAL3);
    #else
          printf("%d is less than %d and %d\n", VAL1, VAL2, VAL3);
    #endif
    return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  10 is less than 20 and 30




3 comments:

  1. if Val1 = Val2 = Val3 What will happen???

    ReplyDelete
  2. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from

    ReplyDelete