Example of macro function in C – Includes multi-line macro

Program examples of macro function in C language. Also, includes program example of multi-line macro function.

Macro functions example:

This C program demonstrate use of multiple macro functions e.g. ABS, MAX and AVERAGE.


/*---------------------------------------------------
program examples of MACRO FUNCTIONS in C programming
*/
#include<stdio.h>

//Macro function returning absolute value
#define ABS(x)           (((x) < 0) ? -(x) : (x))

//macro function to find max value between 2 number
#define MAX(a,b)         ((a < b) ?  (b) : (a))

//macro function to fine average of two numbers
#define AVERAGE(x,y) (((x)+(y))/2.0)


int main ()
{

      int a =20;
      int b =10;

      printf ("Absolute value :%d\n", ABS(-2));

      printf("Max number between a and b is = %d\n", MAX(a,b));

      printf ("Average of 2 numbers =:%d\n", AVERAGE(a,b));

      return 0;

}

Output:

Absolute value :2
Max number between a and b is = 20
Average of 2 numbers =:0

Multiline Macro functions example in C

This C program demonstrate that a macro function can have multiple lines in it.


/*---------------------------------------------------
program examples of MULTILINE MACRO FUNCTIONS in C
*/
#include<stdio.h>

//multi line macro function
#define DISPLAYMATH(a, b) {\
            printf("%d\n", a+b);\
            printf("%d\n", a*b);\
            printf("%d\n", a/b);\
            printf("\n");\
           }

int main ()
{
      int a =20;
      int b =10;

      DISPLAYMATH(a,b);

      return 0;

}

Output:
30
200
2

Related Posts