Topic 80 of 83
Preprocessor
Overview
The Preprocessor runs *before* the compiler. It modifies the source code by including files, replacing macros, and performing conditional compilation.
Syntax
cpp
#include <iostream> // Copies standard library file
#include "myMath.h" // Copies your own local header file
#define PI 3.14159 // Replaces all instances of 'PI' with '3.14159'
// Conditional Compilation (Header Guards)
#ifndef MY_CLASS_H
#define MY_CLASS_H
class MyClass {};
#endifCommon Pitfalls
- Using `#define` for constants instead of `const` or `constexpr`. Macros are dumb text replacements; they don't obey scope and have no data type, leading to horrific bugs.
Interview Tips
- Explain Header Guards (`#ifndef`, `#define`, `#endif` or `#pragma once`). They prevent a header file from being included twice in the same translation unit, which would cause 'redefinition' errors.
Real-World Example
Using macros for conditional debugging.
example
cpp
#include <iostream>
using namespace std;
#define DEBUG_MODE 1
int main() {
#if DEBUG_MODE
cout << "[DEBUG] System initialized.\n";
#endif
cout << "Standard output.\n";
return 0;
}