CodeBlanks Logo Icon CodeBlanks

Conditional compilation

  • C course
  • Beginner
  • Lesson 108/116
  • 5 min

Learn conditional compilation with #ifdef, #ifndef and #endif.

Conditional compilation: #ifdef, #ifndef, #endif

#ifdef compiles code if a macro is defined; #ifndef compiles if it is not. #endif closes the block.

#define DEBUG

#ifdef DEBUG
    printf("debug");
#endif

Here if DEBUG is defined, the printf is compiled; otherwise it is skipped. This is useful to remove debug code from production builds. With #ifndef you can run custom code when a macro is missing. This allows producing different builds from a single source.

Conditional definition with #ifndef

#ifndef compiles its content if a macro is not defined. This is useful to give a constant a default value.

#ifndef VERSION
    #define VERSION 1
#endif

Here if VERSION was not previously defined, it becomes 1. The compiler can give a different value from the command line with -DVERSION=2. This is also used as include guard in header files; we will see it later. It is an important tool for writing flexible and portable code.

Practice Conditional print with the DEBUG macro

Define a macro with #define DEBUG. In main use #ifdef DEBUG to print printf("debug\n"); close the block with #endif.

Starter code

main.c
#include <stdio.h>

// Define the DEBUG macro
int main(void) {
    // If DEBUG is defined print debug with printf; close the block
    return 0;
}

Sample solution

main.c
#define DEBUG
#ifdef DEBUG
printf("debug\n");
#endif

Expected output

debug

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: #ifdef block

Question
#ifdef DEBUG
    printf("debug");
____
Answer
#ifdef DEBUG
    printf("debug");
#endif

Explanation: #endif closes the #ifdef block.

2 Match directive to meaning

Term Meaning
#ifdef X If X is defined
#ifndef X If X is not defined
#endif Ends the block
#define X Defines X

3 What does #endif do?

  • Starts an #ifdef block
  • Terminates the program
  • Declares a variable
  • Ends an #ifdef block Correct answer

Explanation: #endif closes an #ifdef or #ifndef block.

All lessons in Beginner