Holla Tech - Learn

The #ifdef, #ifndef, and #undef Directives
 

The #ifdef, #ifndef, and #undef directives operate on macros created with #define.
For example, there will be compilation problems if the same macro is defined twice, so you can check for this with an #ifdef directive. Or if you may want to redefine a macro, you first use #undef.

The program below demonstrates these directives: 

#include <stdio.h>

#define RATE 0.08
#ifndef TERM
  #define TERM 24
#endif

int main() {
  #ifdef RATE  /* this branch will be compiled */
    #undef RATE 
    printf(“Redefining RATE\n”);
    #define RATE 0.068
  #else  /* this branch will not be compiled */
    #define RATE 0.068
  #endif

  printf(“%f  %d\n”, RATE, TERM);

  return 0;
}

 

Because RATE is defined at the top, only the #ifdef clause will be compiled. The optional #else branch compiles when #ifdef RATE is false during preprocessing.
An #endif is required to close the block of code.

NOTE!
An #elif directive is like an else if and can be used to provide additional alternatives after #else.

Conditional Compilation Directives
 

Conditional compilation of segments of code is controlled by a set of directives: #if, #else, #elif, and #endif.

For example:

#define LEVEL 4

int main() {
  #if LEVEL > 6
    /* do something */
  #elif LEVEL > 5
    /* else if branch */
  #elif LEVEL > 4
    /* another else if */
  #else
    /* last option here */
  #endif

  return 0;

 

There are instances where such conditional compilation can be useful, but this type of code should be used sparingly.
The defined() preprocessor operator can be used with #if, as in:

#if !defined(LEVEL)
  /* statements */
#endif 

 

The #if and if statement are not interchangeable. The #if is evaluated using data available to the preprocessor, which then sends only the true branch for compilation.

NOTE!
An if statement uses data provided at runtime with the possibility of branching to any else clause.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT