Macros vs Functions
Macros are pre-processed which means that all the macros would be processed before your program compiles. However, functions are not preprocessed but compiled.
See the following example of Macro:
#include<stdio.h>
#define NUMBER 10
int
main()
{
printf
(
"%d"
, NUMBER);
return
0;
}
Output:
10
See the following example of Function:
#include<stdio.h>
int
number()
{
return
10;
}
int
main()
{
printf
(
"%d"
, number());
return
0;
}
Output:
10
Macros are pre-processed which means that all the macros would be processed before your program compiles. However, functions are not preprocessed but compiled.
See the following example of Macro:
#include<stdio.h> #define NUMBER 10 int main() { printf ( "%d" , NUMBER); return 0; } |
Output:
10
See the following example of Function:
#include<stdio.h> int number() { return 10; } int main() { printf ( "%d" , number()); return 0; } |
Output:
10
Difference between macro and function
No | Macro | Function |
1 | Macro is Preprocessed | Function is Compiled |
2 | No Type Checking | Type Checking is Done |
3 | Code Length Increases | Code Length remains Same |
4 | Use of macro can lead to side effect | No side Effect |
– | ||
5 | Speed of Execution is Faster | Speed of Execution is Slower |
6 | Before Compilation macro name is replaced by macro value | During function call , Transfer of Control takes place |
7 | Useful where small code appears many time | Useful where large code appears many time |
8 | Generally Macros do not extend beyond one line | Function can be of any number of lines |
9 | Macro does not Check Compile Errors | Function Checks Compile Errors |
No comments:
Post a Comment