Macros in C

by | Aug 13, 2022 | C

Home » C » Macros in C

Macros are almost the same as functions with a little bit of difference. ‘Macros’ definitions are written outside the ‘main’ function by using ‘#define’. We can pass arguments in macros.

#define area(s) (s*s)

We have defined a macro named ‘area’, which is taking ‘s’ as an argument, and its value is ‘s*s’. When we call area(s) in our program, it will get replaced by (s*s).

Program

#include<stdio.h>
#define area(s) (s*s)
int main()
{
int side;
printf("Enter the side of square\n");
scanf("%d",&side);
float A=area(side);
printf("Area of square is %.2f",A);
return 0;
}

 

Output

The code works so well, and we got the desired output.

The above code is equivalent to:

Alternative Program

#include<stdio.h>
int main()
{
int side;
printf("Enter the side of square\n");
scanf("%d",&side);
float A=side*side;
printf("Area of square is %.2f",A);
return 0;
}

 

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author