Why is the 'max' macro defined like this in C?
#define max(a,b) \
({ typ开发者_StackOverfloweof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
Why not simply (a>b ? a : b)
?
because otherwhise max(f(1), f(2))
would call one of the two functions twice:
f(1) > f(2) ? f(1) : f(2)
instead by "caching" the two values in _a
and _b
you have
({
sometype _a = (a);
sometype _b = (b);
_a > _b ? _a : _b;
})
(and clearly as other have pointed out, there is the same problem with autoincrement/autodecrement)
I don't think this is supported by Visual Studio in this way. This is a compound statement. Read here does msvc have analog of gcc's ({ })
I'll add that the definition of compound statement in the gcc manual given here http://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC62 shows a code VERY similar to the one of the question for max :-)
It's getting around the major problem of things like
#define max(a,b) ((a) > (b) ? a : b)
when you call it with:
int x = max (a++, b--);
Since it's simple text substitution, that results in:
int x = ((a++) > (b--) ? a++ : b--);
which is not what you want.
By using:
#define max(a,b) ({
typeof (a) _a = (a);\
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
it uses temporary variables that effectively giving you:
int x = ({ int _a = a++; int _b = b--; _a > _b ? _a : _b; })
which runs the side effects only once.
But, to be honest, you should ditch that macro altogether and use an inline
function, or even a non-inline function since, most of the time, the compiler can do a decent job of optimisation even without that suggestion.
Another way to determine max (at least for positive numbers)
#define MAX(a,b) sizeof(union x { char ca[a]; char cb[b];})
As a and b are accessed only once, MAX(a++,b++) gives the correct result.
If the macro is called with expression, this might lead to unexpected behaviour. Assume this:
int c = max(i++, j++);
In this case, the max is increase twice with the simpler version.
精彩评论