gpt4 book ai didi

c - 使用哪个更安全? "==TRUE"或 "!= FALSE"

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

比较 boolean 类型变量是否更好:

  1. == FALSE!= FALSE;或
  2. == TRUE!= TRUE?

最佳答案

Is it better to compare a boolean type variable with " == FALSE" and " != FALSE" or with " ==FALSE" and " ==TRUE" ?

  1. 都没有。

使用 C boolean 类型 _Bool , 不要使用 ==!=根据常量评估真实性。
@Steve Summit @Antti Haapala @John Bode

_Bool x;
if (x) // to assess truth-ness
if (!x) // to assess false-ness
  1. 如果强烈希望使用 == , != ,与许多风格问题一样,最好遵循您所在小组的编码指南。

  2. 缺少组的编码指南 - 制定它们。


使用 <stdbool.h>能够访问bool, true, false而不是代码 TRUE , FALSE .
@Eugene Sh.


Which one is safer to use? “ ==TRUE” or “ != FALSE”

注意比较a == TRUE可能会意外失败,因为操作数是作为整数、FP 或指针而不是 boolean 值进行比较的。这可能无法比较真实性应该 a是具有非 1 的“真实”值的非 boolean 值,即使 TRUE是一个 boolean 值 1。

double a = 0.999999;
// Both are false
if (a == TRUE) { ... } // The arithmetic value of `a` is used, not its "truth"
if (a == FALSE) { ... }
// better as
if (a) { ... } // As if `a != 0`
else { ... }

考虑“真相”返回为非零,可能不是 1 的情况。

if(islower('a') == TRUTH) ...  // The if() block might or might not execute
if(islower('a')) ... // The if() block will execute

a != 0a != false往往更安全。


样式:我找到==代码比 != 更容易理解因为否定会增加人们的心理复杂性。 Example

关于c - 使用哪个更安全? "==TRUE"或 "!= FALSE",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014718/

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