Macros
#define NAME value simple constant macros banata hai — jaha bhi NAME likha hai, preprocessor use "value" se replace kar deta hai, function call ki tarah nahi (koi runtime overhead nahi, kyunki ye compile-time par hi ho jaata hai).
Function-like macros parameters bhi le sakte hain: #define SQUARE(x) ((x) * (x)). Real functions se farq: macros ka koi type-checking nahi hota, aur ye "inline" expand ho jaate hain (function call overhead nahi) — lekin agar galat likhe jaayein to unexpected bugs de sakte hain.
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
int main() {
printf("%f\n", PI); // 3.14159
printf("%d\n", SQUARE(5)); // 25
int a = 5;
printf("%d\n", SQUARE(a + 1)); // ((a+1)*(a+1)) = 36, sahi (parentheses ki wajah se)
return 0;
}- #define = compile-time text substitution, koi runtime cost nahi
- Function-like macros parameters le sakte hain
- Macro parameters ko hamesha () mein wrap karo — warna operator precedence bugs
Macros normally ek line ke hote hain, lekin backslash (\) line ke end mein daalkar macro ko multiple lines tak extend kar sakte ho — preprocessor unhe ek hi logical line ki tarah treat karta hai.
#define PRINT_INFO(name, age) \
printf("Name: %s\n", name); \
printf("Age: %d\n", age)
int main() {
PRINT_INFO("Aarav", 20);
return 0;
}# operator (stringizing) macro parameter ko ek string literal mein convert kar deta hai. ## operator (token pasting) do tokens ko jodkar ek naya token banata hai. Ye advanced macro tricks hain, jo mostly debugging utilities ya code-generation macros mein dikhte hain.
#define STRINGIFY(x) #x
#define CONCAT(a, b) a##b
int main() {
printf("%s\n", STRINGIFY(hello)); // "hello" (string ban gaya)
int CONCAT(my, Var) = 10; // ban jaata hai: int myVar = 10;
printf("%d\n", myVar); // 10
return 0;
}