哪个更安全使用? " == TRUE"或"!= FALSE" [英] Which one is safer to use? " ==TRUE" or " != FALSE"

查看:111
本文介绍了哪个更安全使用? " == TRUE"或"!= FALSE"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将布尔类型变量与以下内容进行比较是否更好?

Is it better to compare a boolean type variable with:

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

推荐答案

将布尔类型变量与"== FALSE"和!= FALSE"或与"== FALSE"和"== TRUE"进行比较是否更好?

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

  1. 都不是.

对于C布尔类型_Bool,请勿使用==!=评估真实性.
@Steve Summit @Antti Haapala

With the C boolean type _Bool, do not use == or != to assess truth-ness.
@Steve Summit @Antti Haapala @John Bode

_Bool x;
if (x)   // to assess truth-ness
if (!x)   // to assess false-ness

  1. 如果仍然强烈希望使用==!=,就像许多样式问题一样,最好遵循小组的编码准则.

  1. If a strong desire remains to use ==, !=, like many style issues, best to follow your group's coding guidelines.

缺少小组的编码准则-制定准则.

Lacking group's coding guidelines - make them.


<stdbool.h>用于访问bool, true, false,而不要使用代码TRUEFALSE.
@Eugene Sh.



Use <stdbool.h> as able to access bool, true, false rather than code TRUE, FALSE.
@Eugene Sh.

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

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

请注意,比较a == TRUE可能会意外失败,因为操作数将被比较为整数,FP或指针,而不是布尔值.即使TRUE是布尔值1,即使a是具有非1的真"值的非布尔值,这也可能无法比较真实性.

Note that comparing a == TRUE can fail unexpectedly as the operands are compared as integers, FP or pointers, not as boolean. This may fail to compare truth-ness should a be a non-boolean with a "truth" value other than 1 even if TRUE is a 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)的情况.

Consider cases where the "truth" is returned as non-zero, perhaps not 1.

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

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

样式:我发现==代码比!=更易于遵循,因为否定会增加人们的思维复杂性. 示例

Style: I find == code easier to follow than != as negations add mental complexity for people. Example

这篇关于哪个更安全使用? &quot; == TRUE"或"!= FALSE"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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