Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Where are MIN and MAX defined in C, if at all? (如果有的话,在C中定义的MINMAX在哪里?)

What is the best way to implement these, as generically and type safely as possible? (一般地并安全地键入这些内容的最佳方法是什么?) (Compiler extensions/builtins for mainstream compilers preferred.) ((首选主流编译器的编译器扩展/内置插件。))

  ask by Matt Joiner translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

Where are MIN and MAX defined in C, if at all? (如果有的话,在C中定义的MINMAX在哪里?)

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. (我不会使用#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))类的宏,特别是如果您打算部署代码。) 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 : (您可以编写自己的代码,使用标准fmaxfmin类的东西,或者在GCC语句表达式中使用GCC的typeof来修复宏(您也可以获得类型安全性奖励):)

 #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 : (注意使用__typeof__代替typeof :)

If you are writing a header file that must work when included in ISO C programs, write __typeof__ instead of typeof . (如果要编写的标头文件包含在ISO C程序中时必须工作,请编写__typeof__而不是typeof 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...