且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C 中的 MIN 和 MAX

更新时间:2021-12-29 08:21:56

MINMAX 在 C 中定义在哪里,如果有的话?

Where are MIN and MAX 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)) 这样的宏,特别是如果你打算部署你的代码.要么自己写,要么使用标准的fmaxfmin,或修复使用 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 of typeof.