C 中的 MIN 和 MAX [英] MIN and MAX in C
问题描述
MIN
和 MAX
在 C 中定义在哪里,如果有的话?
Where are MIN
and MAX
defined in C, if at all?
实现这些的最佳方法是什么,尽可能通用和安全地键入?(首选主流编译器的编译器扩展/内置函数.)
What is the best way to implement these, as generically and type safely as possible? (Compiler extensions/builtins for mainstream compilers preferred.)
推荐答案
MIN
和MAX
在 C 中定义在哪里,如果有的话?
Where are
MIN
andMAX
defined in C, if at all?
他们不是.
实现这些的最佳方法是什么,尽可能通用且类型安全(首选主流编译器的编译器扩展/内置函数).
What is the best way to implement these, as generically and type safe as possible (compiler extensions/builtins for mainstream compilers preferred).
作为函数.我不会使用像 #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
这样的宏,特别是如果你打算部署你的代码.要么自己写,要么使用标准的fmax
或 fmin
,或修复使用 GCC 的 typeof 的宏(你得到类型安全奖励也)在 GCC 语句表达式中:
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.
注意使用 __typeof__
而不是 typeof
:
Note the use of __typeof__
instead of typeof
:
如果你正在写一个头文件包含在 ISO C 中时必须工作程序,写 __typeof__
而不是typeof
.
If you are writing a header file that must work when included in ISO C programs, write
__typeof__
instead oftypeof
.
这篇关于C 中的 MIN 和 MAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!