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 << PlusOneMacro(5) << '
';   cout << PlusOneFunction(5) << '
';   return 0;}
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.

See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist