DEV Community

Cover image for Macro Vs Function
Dhanashree Rugi
Dhanashree Rugi

Posted on • Edited on

Macro Vs Function

Macro Function
It is a fragment of code given a name macro and is defined by the preprocessor directive #define. In the program before compilation, the macro is replaced by its macro value (or text). It is a set of instructions enclosed within a flower ({}) bracket. When a function is called, it performs the specific task and returns to the main program.
It is preprocessed. It is compiled.
Macros makes the code lengthy if its value is large because macros will be replaced with its value before compilation. The repeated call to function does not affect the code length as it is written only once.
The program execution time remains unaffected using macro Here, the passing of parameters and returning of values takes some time and hence the program execution becomes slow.
In a program, if the macro is appearing at multiple places then it is always a better idea to change that macro into a function because macros will be replaced with its value which causes more memory consumption. In a program, calling the same function repeatedly does not affect the memory consumption.
No type checking (like incompatible data type, operand etc.) is done during preprocessing hence more prone to error. Type checking is done during compilation.

If you find any comparison other than these then please do suggest.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Macros are never "called." You don't explain to a beginner what "preprocessed" means. Saying program execution becomes slow for functions is ridiculously disingenuous. Macros do not consume memory!

There are much better explanations of macros all over the place online. Why even bother? Why not explain something that is not all over the place?

Collapse
 
dhanashreerugi profile image
Dhanashree Rugi

Thanks for suggestions.