Following are two programs that give the area of the circle when the radius is passed as argument. But in the first program, macro.c, I am using a macro for the job, while in the second, function.c I am using a function for the job.
I am familiar with the use of functions,and the nuances it takes. But what about the case of macros that accept arguments? When should we prefer them over functions? And when should we avoid them? Which one gives better performance? I know the macro approach will lead to bulky code if the macro is used many times in the program, while for the case of the function, the same function is invoked many times for the job. But beyond this trivial difference, what are the other issues we need to look out for?
//macro.c
#include<stdio.h>
#define AREA(x) (3.14*x*x)
int main(void)
{
float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\nArea of circle=%f",a);
a=AREA(r2);
printf("\nArea of circle=%f",a);
}
//function.c
#include<stdio.h>
float area(float);
int main(void)
{
float r1=6.25,r2=2.5;
printf("\nArea of circle=%f",area(r1));
printf("\nArea of circle=%f",area(r2));
}
float area(float radius)
{
return 3.14*radius*radius;
}