Macros vs Functions
Macros are preprocessed, meaning that all the macros would be executed before 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 use of macros can lead to errors/side-effects in some cases. This is not the case with functions. Macros do not check for compilation error.
- Macros are usually one liner. However, they can consist of more than one line there are no such constraints in functions.
- The speed at which macros and functions differs. 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 effect at later stages |
Functions do not lead to any side effect in any case |
Speed of Execution using Macro is Faster |
Speed of Execution using Function is Slower |
Before Compilation, 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 |