Complex macro with arguments (function like macro) in C language

Here, we will learn how we can define a complex macro which looks like a user define function in c programming language?

We can also define a macro with arguments, so that a macro may use at different places with different values. These values pass in the macro definition with the help of arguments.

Arguments must be used each time of macro calling.

This type of macro seems like a function; hence we can say that this is the "Function Like Macro Definition".

Syntax

#define macro_name(argument_list) code_fragment

Here,

  • #define is a pre-processor directive
  • macro_name is the name of macro
  • argument_list is the list of arguments
  • code_fragment is the statement which is compiled at the place of the macro

Consider the following statement (as example code of complex macro)

#define SUM(A,B)    (A+B)  

Here, SUM is complex macro where A and B are the input arguments and the statement (A+B) is the code fragment which. At the time of compilation, compiler will replace the macro SUM with its code fragment (A+B).

C program demonstrating example of complex macro

#include<stdio.h>
 
#define SUM(A,B)    (A+B)       // addition of two numbers
#define AVG(A,B)    ((A+B)/2)   // average of two numbers
#define MAX(A,B)    ((A>B)?A:B)  // largest number
 
int main()
{
    int num1,num2;
    printf("Enter first number : ");
    scanf("%d",&num1);
    printf("Enter second number: ");
    scanf("%d",&num2);
 
    printf("Sum is = %d\n",SUM(num1,num2));
    printf("Average  is = %d\n",AVG(num1,num2));
    printf("Largest Number is = %d\n",MAX(num1,num2));
    return 0;
}

Output

Enter first number : 10 
Enter second number: 20 
Sum is = 30 
Averageis = 15
Largest Number is = 20



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.