Reputation: 7
Is "inline" safer, or less safe than using a pre-compiler definition for "max" (see below)?
#define max(a,b) (a > b) ? a : b
Given this function definition:
inline int max (int a, int b)
{
return (a > b) ? a : b;
}
Upvotes: 0
Views: 166
Reputation: 96281
The macro version will evaluate its arguments multiple times which will result in semantic difference (error) if the argument has side effects (like calling a non-const function).
Further the arguments aren't each enclosed in parens so there may be other ways you can concoct parameters such that precedence completely changes the meaning of what's being attempted. For example max(c, x < y)
would fold out as (c > x < y) ? c : x < y
which will evaluate c > x
and then compare the truth of that against y
. That's completely not what was intended.
The inline function on the other hand works only with integral types without truncations.
A better approach is to not reinvent the wheel and use std::max
which takes care of all the problems above and is handily provided by your implementation.
Upvotes: 4
Reputation: 311048
The macro has many negative side-effects. For example consider
max( ++a, b );
Upvotes: 1
Reputation: 477348
There's a semantic difference:
max(pay_wife(1000), get_salary());
Upvotes: 8