Macros in C (#define)
Macros are preprocessor directives used to define constants, functions, or expressions before the compilation starts.
A macro is replaced directly in the source code by the preprocessor, improving performance and reducing repeated code.
What is a Macro?
A macro is a rule or pattern that replaces specific text in your program before actual compilation. It is handled by the C Preprocessor.
- Begins with
#define - No semicolon at the end
- Faster than functions (no function call overhead)
- Used for constants, short expressions, reusable code blocks
Types of Macros
- Object-like Macros – simple constants
- Function-like Macros – behave like inline functions
- Parameterized Macros – accept values like arguments
- Multi-line Macros – used for long expressions
- Predefined Macros – built-in macros
1. Object-like Macro
These macros represent a constant value.
#include <stdio.h>
#define PI 3.1415
#define MAX 100
int main() {
printf("PI = %.4f\n", PI);
printf("Max limit = %d", MAX);
return 0;
}
2. Function-like Macro
Looks like a function but expands as text.
#include <stdio.h>
#define SQUARE(x) (x * x)
int main() {
printf("Square of 6 = %d", SQUARE(6));
return 0;
}
3. Parameterized Macro
Macros that accept multiple arguments.
#include <stdio.h>
#define ADD(a,b) (a + b)
#define MULT(a,b) (a * b)
int main() {
printf("Add = %d\n", ADD(3,4));
printf("Multiply = %d", MULT(3,4));
return 0;
}
4. Multi-line Macro
Create a multi-statement macro using backslash ( \ ).
#include <stdio.h>
#define SHOW(x) \
printf("Value = %d\n", x); \
printf("Double = %d\n", x * 2);
int main() {
SHOW(5);
return 0;
}
5. Predefined Macros
C provides several built-in macros:
__DATE__– compilation date__TIME__– compilation time__FILE__– current file name__LINE__– current line number__STDC__– compiler follows STD C
Example
#include <stdio.h>
int main() {
printf("File: %s\n", __FILE__);
printf("Line: %d\n", __LINE__);
printf("Date: %s\n", __DATE__);
printf("Time: %s\n", __TIME__);
return 0;
}
When to Use Macros?
- To define constant values
- To improve performance (no function overhead)
- For debugging and logging
- For conditional compilation
- To reduce code repetition
âš NOTE: Macros do not follow scope rules.
Once defined, they apply until #undef is used or the file ends.
Practice Questions
- What is a macro? Explain with examples.
- Differentiate object-like and function-like macros.
- Write a macro to calculate area of a triangle.
- Explain predefined macros.
- What are the advantages of using macros?
Practice Task
Write a macro SWAP(a, b) to swap two numbers without using a temporary variable.