The basic similarities between macros and functions are
1. Both are declared and defined outside the ‘main’ function.
2. Both are called inside the ‘main’ function when needed.
The basic difference between both of them is based on the compilation. Functions are called during compilation, whereas Macros are called before compilation.
We have just seen an example of printing the area of a square using Macros. Now let’s write the same code using Functions.
Table of Contents
Program
#include<stdio.h> float area_square(float s) { float A=s*s; return A; } int main() { float side,area; printf("Enter the value of side of square:\n"); scanf("%f",&side); area=area_square(side); printf("Area of square is : %.2f\n",area); return 0; }
Output
So, you can compare the codes written in different ways. The approach is different, but the goal is the same.
Hopefully, the above-written code is clear to you because we had already done this in the functions chapter.
Differences between the two codes written with Macros and Functions.
The first difference is that Macros replace the code by their value as it replaces ‘area(r)’ with (3.14*r*r). It means that it will be allocated with some space in the memory whenever ‘area(r)’ appears. But this never happens in Functions.
Moreover, macros are always defined before the actual program. Due to this, their call never takes much time. Thus Macros are faster. But functions are not necessarily defined before the ‘main’ functions. Sometimes they are declared before the actual program, but the definition is made after the ‘main’ function. So, in such cases, the function call takes some time.
0 Comments