QUESTION 34 · Qualifiers and Preprocessor
Explain object-like and function-like macros with precautions.
5 marksAnswer in brief
A macro is a name with replacement tokens processed by the preprocessor. It may be object-like or function-like.
Object-like macro
#define LIMIT 100
Function-like macro
#define SQUARE(x) ((x) * (x))
Expansion example
SQUARE(2 + 3) expands to ((2 + 3) * (2 + 3)), giving 25. Without the parameter parentheses, an expansion such as 2 + 3 * 2 + 3 would give 11. The outer parentheses also protect the full result when it is placed inside another expression.
Repeated evaluation
The parameter x occurs twice in SQUARE. Therefore its argument expression also appears twice after replacement. Do not write SQUARE(i++): the resulting expression modifies i without the ordering required by C and has undefined behaviour. Parentheses do not solve that problem. A typed function such as int square(int x) evaluates an argument once before using its parameter.
Comparison with functions
A function has a declared interface, parameter objects and a return type. A macro is token replacement and does not provide the same parameter type checking. A compiler may inline a real function, so do not assume a macro must be faster. Prefer a function for ordinary calculations unless a macro is specifically useful.
Other points
There must be no space between a function-like macro name and the opening parenthesis in its definition. #undef SQUARE removes the definition for later source. Avoid an accidental trailing semicolon in a simple expression macro.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main(void)
{
printf("Square = %d\n", SQUARE(2 + 3));
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Square = 25