doubt

what's the difference between macro and functions?
What's the advantage and disadvantage of each one?
Show me an example showing the diference if possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define OPERATION(a,b) a*b

int Operation(int a, int b)
{
	return(a*b);
}

 //...

int main()
{
	cout << OPERATION(3+2, 4+5) << endl; //shows 16 
	cout << Operation(3+2, 4+5) << endl; //shows 45
}


Why? Because the macro expands it to 3+2*4+5, which is most certainly not what you wanted.

Functions are a nice thing to have because of how they can actually modify things through expressions, while that is more complicated otherwise.
Last edited on
Macros are textual substitutions performed during the preprocessing phase.

The advantage of macros over non-inlined functions is that you avoid the overhead of a function call
and return. The disadvantage of macros are the subtle side effects that can happen. L B gave just
one example. The canonical example is this one:

1
2
3
4
5
6
7
8
#define MIN( a, b ) a < b ? a : b

int main() {
    int a = 5;
    int b = 6;

    std::cout << MIN( a++, b++ ) << std::endl;
}


What is the value of a and b at the end of the program? Hint: it is NOT 6 and 7.

For this reason alone inline functions are *always* preferred to macros.

EDIT: And for that matter, what value is output by the cout statement above?
Last edited on
Yet more reasons to avoid macros:

macros ignore language scope rules and pollute the global namespace, which can lead to some very nasty and bizarre bugs. Consider the folliowing:

1
2
3
4
5
6
7
8
#include <iostream>
#include "someheader.h"

int main()
{
  int MYVAR = 5;
  std::cout << MYVAR;
}


Seems harmless, right... but what if someheader.h looks like this:

 
#define MYVAR     16 


This would cause the compiler to throw all kinds of errors at you.
Last edited on
Topic archived. No new replies allowed.