Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Jun 16, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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) << '\n';
   cout << PlusOneFunction(5) << '\n';
   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.
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date