gpt4 book ai didi

c - C语言中的最小值和最大值

转载 作者:太空狗 更新时间:2023-10-29 16:13:40 25 4
gpt4 key购买 nike

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)) 这样的宏,特别是如果您计划部署您的代码。要么自己写,要么使用类似标准的东西 fmax fmin ,或使用 GCC's typeof 修复宏(你也获得了类型安全奖励)在 GCC statement expression 中:

 #define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })

每个人都说“哦,我知道双重评估,这没问题”,几个月后,您将连续几个小时调试最愚蠢的问题。

注意 __typeof__ 的使用而不是 typeof :

If you are writing a header file that must work when included in ISO C programs, write __typeof__ instead of typeof.

关于c - C语言中的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3437404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com