c
  1. c-preprocessor-test

C Preprocessor Test

Syntax

#ifdef MACRO
   // code to be executed if MACRO is defined
#else
   // code to be executed if MACRO is not defined
#endif

Example

#include <stdio.h>
#define TEST 10

int main() {
   #ifdef TEST
      printf("TEST is defined\n");
   #else
      printf("TEST is not defined\n");
   #endif
   return 0;
}

Output

TEST is defined

Explanation

The C preprocessor directive #ifdef (which stands for "if defined") tests whether a macro has been defined using a #define statement. If the macro has been defined, the code block between #ifdef and #else is executed. If the macro has not been defined, the code block between #else and #endif is executed.

Use

The #ifdef directive is useful for creating platform-specific code or for debugging purposes. It can also be used to selectively include or exclude code based on certain conditions.

Important Points

  • #ifdef checks whether a macro has been defined using #define.
  • If the macro has been defined, the code block between #ifdef and #else is executed.
  • If the macro has not been defined, the code block between #else and #endif is executed.
  • #ifdef can be used for platform-specific code or for debugging purposes.
  • It can also be used to selectively include or exclude code based on certain conditions.

Summary

The #ifdef directive in C is used to test whether a macro has been defined using #define. It is useful for creating platform-specific code or for debugging purposes. By selectively including or excluding code based on certain conditions, #ifdef can help make your code more versatile and efficient.

Published on: