c
  1. c-ifdef

C #ifdef Directive

Syntax

#ifdef CONSTANT
   // code to be executed if CONSTANT is defined
#endif

Example

#include <stdio.h>

#define VERBOSE 1

int main() {
   #ifdef VERBOSE
      printf("Debugging information:\n");
      printf("x = %d\n", x);
      printf("y = %d\n", y);
      printf("z = %d\n", z);
      printf("\n");
   #endif

   /* rest of the code */
   
   return 0;
}

Output

If the VERBOSE constant is defined, the output of the above example will be:

Debugging information:
x = 10
y = 15
z = 20

If the VERBOSE constant is not defined, there will be no output.

Explanation

The #ifdef directive is a preprocessor directive that allows a section of code to be compiled only if a particular constant has been defined. If the constant is defined, the code between #ifdef and #endif is included for compilation; otherwise, the code is omitted.

Use

The #ifdef directive is used to create code that can be selectively compiled based on the specific needs of the system. It is often used in debugging to define a set of debugging functions that can be turned on or off at compile time.

Important Points

  • The #ifdef directive is a preprocessor directive used to conditionally compile code based on the existence of a defined constant.
  • The #ifdef directive requires the definition of the constant to be checked before including code between #ifdef and #endif.
  • If the constant is defined, the code between #ifdef and #endif is included for compilation; otherwise, the code is omitted.
  • The #ifdef directive is often used in debugging to define a set of debugging functions that can be selectively compiled based on need.

Summary

The #ifdef directive is used to conditionally compile code based on the existence of a defined constant. If the constant is defined, the code between #ifdef and #endif is included for compilation; otherwise, the code is omitted. This directive is useful for optimizing code for specific use cases or debugging purposes. Understanding how to use #ifdef can help you write more efficient and effective C code.

Published on: