Macros With Arguments: C Program


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

Video Tutorial: Macros With Arguments: C Program (Biggest of 2 Numbers)


[youtube https://www.youtube.com/watch?v=TQZ3g7Ne_q4]

YouTube Link: https://www.youtube.com/watch?v=TQZ3g7Ne_q4 [Watch the Video In Full Screen.]

Source Code: Macros With Arguments: C Program

#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

Check Below 2 Source code and it’s output

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

Leave a Reply

Your email address will not be published. Required fields are marked *