MIN和MAX用C [英] MIN and MAX in C

查看:154
本文介绍了MIN和MAX用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 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.)

解决方案

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):

 #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.

这篇关于MIN和MAX用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆