CodeBlanks Logo Icon CodeBlanks

Summary - Preprocessor

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

Combine #define, #include and #ifdef to write a configuration header.

Summary - Preprocessor

In this group you learned preprocessor directives. #define defines constants and macros; #include includes headers; #ifdef/#ifndef/#endif perform conditional compilation. Macro functions take parameters; header files are protected with include guards.

#define PI 3.14
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#ifdef DEBUG
    printf("debug");
#endif

The preprocessor rewrites the code as text before compilation. So it does no type checking; use it carefully. Now you will do an exercise that combines all these directives.

Practice VERSION and PRINT_VERSION macros

Define #define VERSION 3 and #define PRINT_VERSION(v) printf("v%d\n", v). In main call PRINT_VERSION(VERSION).

Starter code

main.c
#include <stdio.h>

// Define VERSION 3 and PRINT_VERSION(v) macros
int main(void) {
    // Call PRINT_VERSION(VERSION)
    return 0;
}

Sample solution

main.c
#define VERSION 3
#define PRINT_VERSION(v) printf("v%d\n", v)
PRINT_VERSION(VERSION);

Expected output

v3

Questions and answers

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

1 Match directive to task

Term Meaning
#define Defines a constant
#include Includes a header
#ifdef Conditional compilation
#endif Ends a block

2 What is the best approach for a constant value?

  • An int variable
  • A static variable
  • A #define macro Correct answer
  • An extern variable

Explanation: A #define macro is suitable for constants.

3 Fill in the blank: #include directive

Question
____ <stdio.h>
Answer
#include <stdio.h>

Explanation: #include <stdio.h> includes standard I/O.

All lessons in Beginner