In this video tutorial lets see how to write macros with arguments. We’ll illustrate finding biggest of 2 numbers by using “Macros with arguments” concept.
Note: Do not leave space between macro template name and the argument list / parenthesis. Also make sure to write the macro expansion inside parenthesis.
Related Read:
Preprocessors In C Programming Language
C Program To Find Area of Circle Using Macro Expansion
Page Contents
#include<stdio.h> #define MAX(x, y) ( x > y ? x : y ) int main() { int a, b; printf("Enter 2 numbers\n"); scanf("%d%d", &a, &b); printf("Biggest of %d and %d is %d\n", a, b, MAX(a, b)); return 0; }
Output 1:
Enter 2 numbers
14
5
Biggest of 14 and 5 is 14
Output 2:
Enter 2 numbers
5
14
Biggest of 5 and 14 is 14
Functions return result after evaluating the expression, but Macros are different. Before compiler compiles the program, preprocessor replaces all the occurrence of Macro template with Macro expansion. So in macros, it won’t return the result, but instead the entire macro expansion gets placed in place of macro template.
So in above C program, printf() becomes:
printf("Biggest of %d and %d is %d\n", a, b, ( a > b ? a : b ));
Related Read:
Biggest of Two Numbers Using Ternary Operator: C
No Parenthesis around macro expansion
#include<stdio.h> #define SQUARE(n) n * n int main() { printf("%f", 64/SQUARE(4)); return 0; }
Output:
64
Parenthesis around macro expansion
#include<stdio.h> #define SQUARE(n) (n * n) int main() { printf("%f", 64/SQUARE(4)); return 0; }
Output:
4
In C programming and in mathematics in general, each arithmetic operation has different precedence. Hence by using parenthesis around macro expansion, it gets the highest precedence.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert