Programming Tutorials

#if and #else in C

By: Nirmal in C Tutorials on 2023-05-11  

In C, #if and #else are preprocessor directives that allow conditional compilation of code based on whether a given macro is defined or not.

Here is the basic syntax for using #if and #else:

#if defined(MACRO_NAME)
   // code to be executed if the macro is defined
   // code to be executed if the macro is not defined

If MACRO_NAME is defined, the code within the first block will be compiled, otherwise the code within the second block will be compiled.

Here is an example:

#include <stdio.h>

#define DEBUG

int main() {
   #ifdef DEBUG
      printf("Debug mode is on\n");
      printf("Debug mode is off\n");

   return 0;

In this example, the macro DEBUG is defined at the beginning of the code. If DEBUG is defined, the message "Debug mode is on" will be printed, otherwise the message "Debug mode is off" will be printed.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in C )

Latest Articles (in C)