Introduction
C language में Macros और Functions दोनों का उपयोग code को reusable और efficient बनाने के लिए किया जाता है।
लेकिन दोनों के काम करने का तरीका अलग होता है:
- Macro → Preprocessor द्वारा compile होने से पहले replace होता है
- Function → Program run होने के समय execute होता है
इसलिए इनके बीच का difference समझना बहुत जरूरी है (exam में अक्सर पूछा जाता है)
1. Macro क्या होता है
Macro एक preprocessor directive (#define) के माध्यम से बनाया जाता है, जो function की तरह दिखता है लेकिन actually text replacement करता है।
Example:
#define SQUARE(x) (x * x)
2. Function क्या होता है
Function एक block of code होता है जो specific task perform करता है और program के run time पर execute होता है।
Example:
int square(int x) {
return x * x;
}
Example Program: Macro vs Function
#include <stdio.h>
// Macro
#define SQUARE(x) (x * x)
// Function
int square(int x) {
return x * x;
}
int main() {
int num = 5;
printf("Using Macro: %d\n", SQUARE(num));
printf("Using Function: %d\n", square(num));
return 0;
}
Program Explanation
इस program में:
Macro Part:
#define SQUARE(x) (x * x)
SQUARE(num)को preprocessor replace करता है:
(num * num)
- यह compile होने से पहले ही change हो जाता है
Function Part:
int square(int x) {
return x * x;
}
- यह function call के समय execute होता है
- memory allocate होती है
- control function के अंदर जाता है
Output:
Using Macro: 25
Using Function: 25
दोनों same result देते हैं, लेकिन working अलग है।
Difference Table: Macros vs Functions
| Point | Macros | Functions |
|---|---|---|
| Definition | #define से define | Normal function syntax |
| Execution | Compile time | Run time |
| Working | Text replacement | Actual execution |
| Speed | Fast (no function call) | थोड़ा slow |
| Type Checking | नहीं होती | होती है |
| Memory | allocate नहीं होती | memory allocate होती है |
| Debugging | मुश्किल | आसान |
| Complexity | Simple tasks | Complex logic |
Important Example (Macro Problem)
Wrong Macro:
#define SQUARE(x) x * x
Use:
SQUARE(2 + 3)
Replace होगा:
2 + 3 * 2 + 3 = 11
Correct Macro:
#define SQUARE(x) (x * x)
अब:
(2 + 3) * (2 + 3) = 25
यही reason है कि macros में brackets जरूरी होते हैं।
When to Use Macro
- Simple calculations
- Small expressions
- Performance critical code
When to Use Function
- Complex logic
- Type safety required हो
- Debugging important हो
- Large programs
Key Points (Exam View)
- Macro → Preprocessor handle करता है
- Function → Compiler और program handle करते हैं
- Macro fast होता है
- Function safe होता है
Conclusion
Macros और Functions दोनों useful हैं, लेकिन उनका use situation के अनुसार करना चाहिए।
- अगर speed important है और task simple है → Macro use करें
- अगर safety, readability और debugging important है → Function use करें
Best practice:
Real-world programming में functions ज्यादा prefer किए जाते हैं।