C #define and Macros – Preprocessor in Action
The #define
directive in C is used to create constants or macros. These are powerful tools that the preprocessor handles before compilation even starts.
🔹 #define Constants
Use #define
to give a name to a constant value. This makes your code easier to read and update.
📝 Example 1: Define a Constant
#include <stdio.h> #define MAX 100 int main() { printf("The max value is: %d\n", MAX); return 0; }
🔹 Macro Functions
Macros can also take parameters, just like functions. But they’re replaced as text, not called like regular functions.
📝 Example 2: Macro Function for Squaring
#include <stdio.h> #define SQUARE(x) ((x) * (x)) int main() { int num = 5; printf("Square of %d is %d\n", num, SQUARE(num)); return 0; }
⚠️ Macro Gotcha
Always use parentheses in macro definitions to avoid surprises during expression evaluation!
🎯 Benefits of Using #define
- Improves readability
- Makes updating values easier
- Macro functions can reduce code repetition
🧠 Recap
#define
is your preprocessor’s way of saying, “Let me handle this before you even blink.” Whether it’s constants or macros, use it wisely for cleaner, more maintainable code!