C Preprocessor and Macros

C Preprocessor and Macros

The C Preprocessor 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 PI 3.14

int main() {
printf("%f", PI);
return 0;
}


✔ Define a macro function:

#define SQUARE(x) (x * x)

int main() {
printf("%d", SQUARE(4)); // Output: 16
return 0;
}


👀 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:

#define DEBUG

#ifdef DEBUG
printf("Debug mode ON\n");
#endif


#ifndef Example:

#ifndef VERSION
#define VERSION 1.0
#endif

#if / #elif / #else

#define AGE 20

#if AGE >= 18
printf("Adult");
#elif AGE >= 13
printf("Teenager");
#else
printf("Child");
#endif


5️⃣ Multi-line Macros

Use \ to continue on the next line:

#define MESSAGE printf("Hello "); \
printf("World!\n");

int main() {
MESSAGE;
return 0;
}


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:

#include <stdio.h>

int main() {
printf("File: %s\n", __FILE__);
printf("Line: %d\n", __LINE__);
printf("Compiled on: %s at %s\n", __DATE__, __TIME__);
return 0;
}


📌 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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *