What is the difference between a macro and a function in C? Please tell me one application where I can use macros and functions?
Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it is used. A function definition occurs only once regardless of how many times it is called.
In C, function-like macros are much similar to a function call. In this type of macro, you can define a function with arguments passed into it. TechVidvan Tutorial: Macros with arguments! In the above example, the compiler finds the name of the macro (AREA(a)) and replaces it with the statement (a*a).
The basic difference is that function is compiled and macro is preprocessed. When you use a function call it will be translated into ASM CALL with all these stack operations to pass parameters and return values. When you use a MACRO, C preprocessor will translate all strings using macro and than compile.
Minus of using macros is that they hide implementation. Its way harder to find bug if have one.
In C (and C++) a macro is a preprocessor directive. This means that before your program starts compiling it will go through and process all your macros. Macros are useful because
Disdvatages
Example
#define INCREMENT(x) x++
A function is a piece of code that can relatively independently be executed and performs a specific task. You can think of it sort of like a mathematical function: a function given a set of inputs will give a particular output. In C these are defined as
<return type> <name>(<parameters>)
{
//code body
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With