Macro and functions

Macro and functions

What is a macro? What is the difference between macros and functions? How do you invoke a macro? Please give an example of code.

A macro is simply an alias for a language expression. Consider the following code:

#define PlusOneMacro(i) ((i) + 1)int PlusOneFunction(int i){   return i + 1;}int main(){   cout This code has a macro and function that both perform the same task. The main difference between the two is that, in the case of the function, execution jumps to the function and returns to the calling code when that function has finished, while in the case of the macro, the C/C++ compiler actually inserts the macro expression at the location it is used.You should use functions when they are long. You don’t want the C/C++ compiler to duplicate the code from long functions everytime they are called. You can use macros when they are short. Macros are slightly faster than functions because the code doesn’t need to jump to another location.


Share the Post: