What are macros in C programming language?



Macro substitution is a mechanism that provides a string substitution. It can be achieved through "#deifne".

It is used to replace the first part with the second part of the macro definition, before the execution of the program.

The first object may be a function type or an object.

Syntax

The syntax for macros is as follows −

#define first_part second_part

Program

In the program for every occurrence of first_part is replaced with the second_part throughout the code.

 Live Demo

#include<stdio.h> #define square(a) a*a int main(){ int b,c; printf("enter b element:"); scanf("%d",&b); c=square(b);//replaces c=b*b before execution of program printf("%d",c); return 0; }

Output

You will see the following output −

enter b element:4 16

Consider another program that explains the functioning of macros.

 Live Demo

#include<stdio.h> #define equation (a*b)+c int main(){    int a,b,c,d;    printf("enter a,b,c elements:");    scanf("%d %d %d",&a,&b,&c);    d=equation;//replaces d=(a*b)+c before execution of program    printf("%d",d);    return 0; }

Output

You will see the following output −

enter a,b,c elements: 4 7 9 37
Updated on: 2021-08-10T19:21:24+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements