What is the difference between macro and function?

Here are the differences between macro and function,

1.Macro consumes less time:
When a function is called, arguments have to be passed to it, those arguments are accepted by corresponding dummy variables in the function. Then they are processed, and finally the function returns a value that is assigned to a variable (except for a void function). If a function is invoked number of times, the times add up, and compilation is delayed. On the other hand, the macro expansion had already taken place and replaced each occurrence of the macro in the source code before the source code starts compiling, so it requires no additional time to execute.

2. Function consumes less memory:
Prior to compilation, all the macro-presences are replaced by their corresponding macro expansions, which consumes considerable memory. On the other hand, even if a function is invoked 100 times, it still occupies the same space. Hence function consumes less memory.

Example for Macro:
The following line defines the macro SUM, having two parameters a and b and the replacement tokens (a + b):

#define SUM(a,b) (a + b)

This definition would cause the preprocessor to change the following statements (if the statements appear after the previous definition):
c = SUM(x,y);
c = d * SUM(x,y);
In the output of the preprocessor, these statements would appear as:
c = (x + y);
c = d * (x + y);

Example for function:
In calling program function call would appear as,


Where sum is the name of the function. And x, y are the arguments passed from calling program to called program.
This statement will invoke the following function SUM. Hence x, y are copied to dummy variables a and b. And then function computes the sum and stores the value in c, which will be returned back to the calling program.

int sum(int a, int b)
int c;
return c;


3 thoughts on “What is the difference between macro and function?

  1. I was not able to understand the macro and function, but your notes help me, and i understand it.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.