哪个更安全使用? " == TRUE"或"!= FALSE" [英] Which one is safer to use? " ==TRUE" or " != FALSE"
问题描述
将布尔类型变量与以下内容进行比较是否更好?
Is it better to compare a boolean type variable with:
-
== FALSE
和!= FALSE
;或 -
== TRUE
和!= TRUE
?
== FALSE
and!= FALSE
; or== 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" ?
- 都不是.
对于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
-
如果仍然强烈希望使用
==
,!=
,就像许多样式问题一样,最好遵循小组的编码准则.
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
,而不要使用代码TRUE
,FALSE
.
@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 != 0
或a != false
往往更安全.
样式:我发现==
代码比!=
更易于遵循,因为否定会增加人们的思维复杂性.
Style: I find ==
code easier to follow than !=
as negations add mental complexity for people. Example
这篇关于哪个更安全使用? " == TRUE"或"!= FALSE"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!