MIN和MAX用C [英] MIN and MAX in C
问题描述
在哪里 MIN
和 MAX
在C中定义,如果在所有?
什么是实现这些,因为一般和尽可能安全地输入的最佳方式? (编译器扩展/内建主流的编译器preferred。)
在哪里
MIN
和MAX
在C中定义,如果在所有?
块引用>他们不是。
什么是实现这些,作为一般和类型安全的,最好的方式(编译器扩展/主流编译器preferred建宏)。
块引用>作为功能。我不会使用像
宏的#define MIN(X,Y)(((X)≤(Y))(X):?(Y))
,尤其是如果您计划部署code。无论是写自己的,使用这样的标准的fmax
或FMIN
,或使用 GCC的typeof运算修复宏(你会得到奖金类型安全太):的#define MAX(A,B)\\
({__typeof__(一)_a =(一); \\
__typeof__(二)_B =(B); \\
_a> _b? _a:_b; })大家都说:哦,我知道约一倍的评价,这是没有问题的,并在几个月在路上,你会被调试的最愚蠢的问题,几个小时就结束。
请注意使用
__ __ typeof运算
而不是的typeof
:
如果你正在写一个头文件
必须包含在ISO C工作时
程序,写__ __ typeof运算
而不是
的typeof
。
块引用>Where are
MIN
andMAX
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.)
解决方案Where are
MIN
andMAX
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 standardfmax
orfmin
, or fix the macro using GCC's typeof (you get typesafety bonus too):#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 oftypeof
:If you are writing a header file that must work when included in ISO C programs, write
__typeof__
instead oftypeof
.
这篇关于MIN和MAX用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!