C Preprocessor and Macros

C Tutorial

C Preprocessor and Macros

The C Preprocessor and Macros runs before the actual compilation of the program.
It processes instructions beginning with the # symbol, called preprocessor directives.

These directives help include files, define constants, create macros, and control compilation.


📌 Common Preprocessor Directives

Directive Purpose
#include Includes header files
#define Defines macros or constants
#undef Removes a defined macro
#ifdef Checks if macro is defined
#ifndef Checks if macro is not defined
#if, #elif, #else, #endif Conditional compilation
#pragma Compiler-specific instructions

1️⃣ #include Directive

Used to insert the contents of another file.

#include <stdio.h> // Standard header
#include "myfile.h" // User-defined header

2️⃣ #define (Macros and Constants)

✔ Define a constant:


 


✔ Define a macro function:


 


👀 Warning: Macro without parentheses can cause errors:

❌ Wrong:

#define SQUARE(x) x * x
printf("%d", SQUARE(2+2)); // Output: 8 (wrong!)

✔ Correct:

#define SQUARE(x) ((x) * (x))

3️⃣ #undef

Removes a defined macro.

#define SIZE 10
#undef SIZE

4️⃣ Conditional Compilation

Used when compiling different environments (debug mode, Windows/Linux, etc.)

#ifdef Example:


 


#ifndef Example:


#if / #elif / #else


 


5️⃣ Multi-line Macros

Use \ to continue on the next line:


 


6️⃣ Predefined Macros

C provides built-in macros:

Macro Meaning
__DATE__ Current compilation date
__TIME__ Current compilation time
__FILE__ Current filename
__LINE__ Line number in file
__STDC__ Whether compiler conforms to ANSI C

Example:


 


 Advantages of Macros

✔ Faster execution (no function call)
✔ Easy constant management
✔ Useful in debugging
✔ Platform-specific compilation


 Disadvantages

❌ Can cause unexpected behavior
❌ Hard to debug
❌ No type checking


🧠 Summary

Feature Example
Constant #define PI 3.14
Macro function #define SQUARE(x) ((x)*(x))
Include file #include <stdio.h>
Conditional compile #ifdef DEBUG

You may also like...