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

DirectivePurpose
#includeIncludes header files
#defineDefines macros or constants
#undefRemoves a defined macro
#ifdefChecks if macro is defined
#ifndefChecks if macro is not defined
#if, #elif, #else, #endifConditional compilation
#pragmaCompiler-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:

MacroMeaning
__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

FeatureExample
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...