In this post, we are going to understand difference between macro and function. But before getting started, I want to explain little bit about macro and function to you in an easy way.
What is a function?
A function can be stated as a group of statements that performs some kind of task. In every C program, you’ll notice at least one function that is main() function. The execution of the program starts from there only. You can divide your code into smaller functions for reducing the size of the body of main() function.
Now let us see the syntax of a function.
return_type function_name(parameter){ //body of the function }
What is a macro?
Macros are used to define symbolic constants. It is a preprocessor directive, which means it replaces itself with the value which is given to it. Let us understand it with an example.
#include <stdio.h> #define X 3 //macro definition int main(){ int x = 10; printf("%d\n", x + X); //here the value of 'X' gets replaced by '3' }
The output of the above code is:
13
Hope you’ve got an idea of macro and its use.
Difference between Macro and Function
Macro | Function |
It is not compiled, it is pre-processed. | It is not pre-processed but it is compiled. |
Macros do not check for compilation error which leads to unexpected output. | Function checks for compilation error and there is a less chance of unexpected output. |
Code length is increased. | Code length remains same. |
Macros are faster in execution than function. | Functions are bit slower in execution. |
Before compilation process the macro name is replaced by the macro value. | In a function call, transfer of control takes place. |
Macros are useful when a small piece of code used multiple times in a program. | Functions are helpful when a large piece of code repeated number of times. |
Comment below if you have queries regarding above tutorial for difference between macro and function.
The post Difference between Macro and Function appeared first on The Crazy Programmer.
from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/03/difference-between-macro-and-function.html
Comments
Post a Comment