Macros in C
In C, a macro is a fragment of code defined by the #define
directive, which acts as a text substitution tool during the preprocessing stage before compilation. Macros help make code more readable, reusable, and sometimes more efficient by reducing repetitive code.
Types of Macros in C
There are two main types of macros:
- Object-like Macros: These are similar to constants or simple code substitutions.
- Function-like Macros: These resemble functions but are simply text replacements without the overhead of a function call.
1. Object-like Macros
Object-like macros are used to define constants or static pieces of code. They do not take any arguments.
#define NAME value_or_code
Explanation:
#define PI 3.14159
definesPI
as a constant.- Everywhere
PI
appears in the code, it will be replaced by3.14159
before the code is compiled.
2. Function-like Macros
Function-like macros work similarly to functions but without the overhead of actual function calls. They are defined with parameters, but they perform only text substitution.
Syntax:
Explanation:
#define SQUARE(x) ((x) * (x))
defines a macro calledSQUARE
that calculates the square ofx
.- When we write
SQUARE(num)
, it gets replaced with((num) * (num))
during preprocessing, effectively calculating the square ofnum
.
Note on Parentheses:
To avoid unexpected results in macros, use parentheses around parameters and the entire expression. For example, without parentheses, SQUARE(2 + 3)
would expand to 2 + 3 * 2 + 3
, giving 11
instead of 25
.
Defining a Maximum Macro
Comments
Post a Comment