views:

172

answers:

6

Discussing with people, asking in interviews, or being asked in interviews, I do not know if I know exactly when to write a function as inline or write it as a macro. Apart from compile-time and run-time consideration, is there any suggestion from coding standard point of view.

I think this is one of those question where it comes to the programmer's preference, or one may say bias towards the usage. I might be a good idea, if members can quote anecdotes, experiences or situations where they have chosen one over the other.

+3  A: 

Here's my thumb rule: Avoid macros.

[Edit] Rationale: Macros should be avoided since they are prone to all sort of problems. For instance:

#define SQUARE(X) ((X)*(X))

int m = 4;
int n = SQURAE(++m)   // m is incremented twice
printf("m=%d n=%d\n", m, n); // output is: 6, 30 where you'd expect 5, 25

If you're thinking of using macros due to performance benefits then inlined functions are probably just as good. Moreover, optimizations should be considered only after you have a well-behaving code that exhibits performance issues. Thus, in 95% of all cases you're better off with plain functions.

Itay
I don't know of any cases where a macro would have better performance than an inline function
Phil Nash
Typo in line 2 of code: says SQURAE should say SQUARE
barrowc
@Phil Nash: I'm not advocating using macros, but a macro is going to be faster for all cases where the inline function is not actually inlined. In otherwords, at least with a macro you are guaranteed that your code is inlined. For example, a compiler may decide not to inline your function if it has a loop or switch statement.
Richard Corden
+4  A: 

Inline is generally preferred, because the inline constants or functions are typed, so mistakes are caught earlier.

It is hard to write bulletproof macros, and they can become quite unreadable in the process.

starblue
+1  A: 

Remember macros are really glorified text substitutions and such are part of the pre-processor .
They have their uses but for me, small functions ( like getters/setters ) are not one of them.
I'd use an inline function over a macro any day as it
1. Compiler enforces type checking of params
2. Much easier to debug

zebrabox
+1  A: 

If you have the choice write a function (possibly inlined). There are some cases where you don't have the choice, and a macro is your only way. Usually even those cases can be avoided by designing around them.

Remember, a macro is not part of the C/C++ core language - it's part of a separate language that knows only about textual manipulations, which runs first and pre-processes the code. It has no knowledge of C/C++ constructs and will blindly substitute text. The scope for errors, some some subtle, some not so subtle, is pretty high.

Even situations where you want a call to be conditionally compiled out (say a debug log) can be achieved with function calls. Just put #ifdef blocks with-in the function and, in most cases, the compiler will optimise the call away if it sees it won't do anything.

Phil Nash
+6  A: 

Macros should be used sparingly, in circumstances where a function will simply not do the job. An example, is error reporting. I use this macro for that purpose:

#define ATHROW( msg )              \
{                   \
    std::ostringstream os;           \
    os << msg;              \
    throw ALib::Exception( os.str(), __LINE__, __FILE__ );   \
}                   \

This has to be a macro in order to get the correct file & line number using the standard __FILE__ and __LINE__ macros , and also to provide the error formatting so I can say things like:

ATHROW( "Value " << x << " is out of range" );
anon
good counter-example. You should definitely check out Alexandrescu's article on Enforcements to take that to the next level: ddj.com/cpp/184403864
Phil Nash
A: 

In C++, avoid macros, and inline to your heart's content. C++ compilers inline very aggressively anyway (partly because template code and the standard library relies on it for performance)

Neil Butterworth pointed out what is more or less the only situation where you'd use a macro. If you need it to fill in the __FILE__ and __LINE__ macros or similar at the call-site.

Macros are error-prone and dangerous - and because they're not functions, they can't, for example, be used with the STL algorithms. So you lose type safety, robustness and flexibility.

And gain nothing whatsoever.

In C, I believe the situation is a bit more mixed, and macros are much more often used.

jalf
Although it's a narrow field, macros can also be useful in making up for the (current) lack of variadic templates in C++. Boost uses its Preprocessor library to help generate the set of Boost.Function overloads for this purpose. That need will go away with C++0x, tho.
Phil Nash
true. Hopefully, the OP won't need to mess with that any time soon though. :)
jalf
hehe, good point
Phil Nash