Difference between Macro and Function in C
Macro | Function |
---|---|
A macro is a preprocessor directive that performs text substitution before the compilation process. | A function is a reusable block of code that performs a specific task when called. |
Macros are defined using the #define directive and do not require a function prototype. |
Functions are declared with a return type, name, and optional parameters, and they may have a function prototype. |
Macros are expanded inline, directly replacing the macro call with its body during preprocessing. | Functions are executed at runtime and can be called multiple times from different parts of the program. |
Macro substitution is a simple textual replacement and does not introduce any overhead. | Function calls involve stack manipulation and parameter passing, which may incur some performance overhead. |
Macros can have arguments and can be parameterized, but they do not perform type-checking. | Functions have typed parameters, and the compiler performs type-checking during compilation. |
Macros can access global variables and manipulate the program at the source code level. | Functions have their own local variables and operate within their scope. |
Macros are not aware of the program structure which can lead to unexpected behavior or side effects. | Functions adhere to the modular programming concept and promote code reusability and maintainability. |
Macros can be used for conditional compilation, code generation, and simple text manipulation. | Functions are used to encapsulate a set of operations and promote code organization and readability. |
Macros are resolved during the preprocessing phase before the compilation of the program. | Functions are resolved during the compilation and linking phases. |
In summary, macros and functions serve different purposes in C programming. Macros are preprocessor directives that perform text substitution before compilation, while functions are reusable blocks of code that perform specific tasks at runtime. Macros provide simple text substitution without type checking and can access global variables, while functions promote modular programming, code reusability, and maintainability. It is important to understand the differences and choose the appropriate approach based on the specific requirements and constraints of the program.