🪄
Preprocessor

Macros

#define — Text Substitution
💡 Macro ek find-and-replace command hai jo pura code compile hone se pehle chal jaata hai — jaise tum Word document mein "find & replace" karte ho, preprocessor tumhare poore code mein macro naam ko uski definition se replace kar deta hai.

#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;
}
🪄
Macro ek find-and-replace command hai jo pura code compile hone se pehle chal jaata hai — jaise tum Word document mein "find & replace" karte ho, preprocessor tumhare poore code mein macro naam ko uski definition se replace kar deta hai.
1 / 2
⚡ झट से Recap
  • #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
इस page में (2 subtopics)

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;
}
⚠️Common Mistake: Multi-statement macros ko do{...}while(0) mein wrap karna best practice hai, warna if-else ke saath use karne par unexpected behavior aa sakta hai (semicolon aur braces ke matching issues).

# 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;
}
💡Tip: Ye operators rarely everyday code mein use hote hain, lekin bade libraries (jaise testing frameworks) mein macro-generated code ke liye common hain — samajhna useful hai jab aisi library ka source padho.