Macros are preprocessed, meaning that all the macros would be executed before the compilation stage. However, functions are not preprocessed but compiled.
Example of Macro:
#include<stdio.h>
#define A 10
int main()
{
printf(“%d”,A);
return 0;
}
OUTPUT=10;
Example of Function:
#include<stdio.h>
int A()
{
return 10;
}
int main()
{
printf(“%d”, A());
return 0;
}
OUTPUT=10;
Now compile them using the command:
GCC –E file_name.c
This will give you the executable code as shown below:
#include<stdio.h>
#define A 10
int main()
{
printf(“%d”,A);
return 0;
}
#include<stdio.h>
int A()
{
return 10;
}
int main()
{
printf(“%d”, A());
return 0;
}
The first program shows that the macros are preprocessed while functions are not.
In macros, no type checking (incompatible operand, etc.) is done, and thus, the use of macros can lead to errors/side-effects in some cases. That is not the case with functions. Macros do not check for a compilation error.
Macros are usually one-liners. However, they can consist of more than one line, and there are no such constraints in functions.
The speed at which macros and functions differ. Macros are typically faster than functions as they don’t involve actual function call overhead.
MACRO | FUNCTION |
Macro is Preprocessed | Function is Compiled |
No Type Checking is done in Macro | Type Checking is Done in Function |
Using Macro increases the code length | Using Function keeps the code length unaffected |
Use of macro can lead to side effects at later stages | Functions do not lead to any side effects in any case |
Speed of Execution using Macro is Faster | Speed of Execution using Function is Slower |
Before Compilation, the macro name is replaced by macro value | During function call, transfer of control takes place |
Macros are useful when small code is repeated many times | Functions are useful when large code is to be written |
Macro does not check any Compile-Time Errors | Function checks Compile-Time Errors |