Where are MIN
and MAX
defined in C, if at all?
They aren't.
What is the best way to implement these, as generically and type safe as possible (compiler extensions/builtins for mainstream compilers preferred).
As functions. I wouldn't use macros like #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
, especially if you plan to deploy your code. Either write your own, use something like standard fmax
or fmin
, or fix the macro using GCC's typeof (you get typesafety bonus too) in a GCC statement expression:
#define max(a,b)
({ __typeof__ (a) _a = (a);
__typeof__ (b) _b = (b);
_a > _b ? _a : _b; })
Everyone says "oh I know about double evaluation, it's no problem" and a few months down the road, you'll be debugging the silliest problems for hours on end.
Note the use of __typeof__
instead of typeof
:
If you are writing a header file that
must work when included in ISO C
programs, write __typeof__
instead of
typeof
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…