Macros of functions

Hi there ! I have a question about macros. I've read that macros can be dangeurous and it's better to use a function than a macro. For example:

a macro like:

#define MAX(a,b) (a > b) ? a : b

is better in a function form like

1
2
3
4
5
6
7
int MAX (int a, int b)
{
   if (a > b)
      return a;
   else
      return b;
}


I dont't think so, I prefer macros.
Why do you prefer macros?
It takes just one line. Are functions faster than macros ?
Thanks for the link.

It's necessary to use inline functions or simple functions like MAX(a, b) ? inlines are faster ?
inlines are faster ?

http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.3

Also, I recommend reading the whole FAQ, you will learn a lot of good practices.
R0mai wrote:
Why do you prefer macros?
littleprogrammer wrote:
It takes just one line
int MAX (int a, int b) { return (a > b) ? a : b; }
Last edited on
@Bazzy: you're right, I got wrong ...

Thanks both . :)
@littleprogrammer:

Just run this code and then tell me macros are better:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

#define MAXIMUM( a, b ) a > b ? a : b

int main() {
    int a = 4;
    int b = 6;
    int c = MAXIMUM( a++, b );
    std::cout << a << ", " << b << ", " << c << std::endl;
}


An inline function is exactly as fast as a macro.

EDIT: removed extra semicolon at end of macro definition as pointed out by PanGalactic
Last edited on
@jsmith: that trailing semicolon on the macro definition means you can't use it in a conditional.

Without this semicolon, this is always fun too:

1
2
int x = MAXIMUM(30, 11) - 20;  // x = 10?
std::cout << "x = " << x << std::endl;

Topic archived. No new replies allowed.