Skip to study material
← Question index

QUESTION 36 · Qualifiers and Preprocessor

Explain conditional compilation and header guards.

5 marks

Answer in brief

Conditional compilation includes or excludes source text according to preprocessing conditions.

Common directives

  1. #if tests a permitted preprocessing constant expression.
  2. #ifdef NAME checks whether NAME is defined.
  3. #ifndef NAME checks whether NAME is not defined.
  4. #elif and #else select alternative groups.
  5. #endif ends the conditional group.

Example explanation

The sample sets DEBUG to 1. #if DEBUG includes the debug message in the translated source, followed by the Ready message. If DEBUG were defined as 0, that debug line would be excluded. In contrast, #ifdef DEBUG would still succeed because the macro would remain defined.

Header guard

#ifndef CODEBHAVYA_SETTINGS_H
#define CODEBHAVYA_SETTINGS_H
/* declarations */
#endif

Why a guard is needed

The first inclusion defines the guard macro and includes the guarded contents. If the same header is included again in that translation unit, the macro already exists, so the contents are skipped. This prevents many repeated declarations or definitions from being processed incorrectly. It does not make an ordinary shared object definition safe to place in every source file; use suitable extern declarations.

Uses and precautions

Conditional compilation can select debug messages, optional features or platform-specific code. Use meaningful project-prefixed macro names and correctly pair each group with #endif. Do not use a runtime variable as though its value were available during preprocessing. A C const int object is not automatically a preprocessing macro or a permitted #if value.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define DEBUG 1
int main(void)
{
#if DEBUG
    puts("Debug enabled");
#endif
    puts("Ready");
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Debug enabled
Ready

Related exam questions

Related questions in the preprocessor category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q3(b) · 8 marks

    What is the use of preprocessor directives? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q1(e) · 2 marks

    Differentiate #undef and #ifndef.

    Paper P02 · page 1

View this category in the exam question bank →