Nested Preprocessor Macro directive having Arguments in C Programming
Contents
How to use Nested Macro ?
- These are Macros having Arguments
- Every time whenever the macro name is encountered , the arguments are replaced by the actual arguments from the program.
- Macro name within another macro is called Nesting of Macro.
Use of Nested Macro :
#define CUBE(x) (SQU(x)*x)
Live Example :
#include<stdio.h> #define SQU(x)((x)*x) #define CUBE(x)(SQU(x)*x) int main() { int x; int y; x = SQU(3); // Argumented Macro y = CUBE(3); // Nested Macro printf("\nSquare of 3 : %d",x); printf("\nCube of 3 : %d",y); return(0); }
Output :
Square of 3 : 9 CUBE of 3 : 27
Explanation :
Program After Expanding SQU(3)
x = SQU(3);
is expanded as -
See This Statement - #define SQU(x)((x)*x) Inside Program Macro Expanded as - x = SQU(3); = ((3)*3)
Program After Expanding CUBE(3)
x = CUBE(3);
is expanded as -
See This Statement - #define SQU(x)((x)*x) #define CUBE(x)(SQU(x)*x) Inside Program Macro Expanded as - y = CUBE(3); = (SQU(3)*3) = (((3)*3)*3)
So overall program after macro expansion will be like this -
int main() { int x; int y; x = ((3)*3); y = (((3)*3)*3); printf("\nSquare of 3 : %d",x); printf("\nCube of 3 : %d",y); return(0); }