72

A comment on this question: Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional? says that you should use !boolean instead of boolean == false when testing conditions. Why? To me boolean == false is much more natural in English and is more explicit. I apologise if this is just a matter of style, but I was wondering if there was some other reason for this preference of !boolean?

25
  • 31
    It is shorter to write.
    – Zenon
    Commented Feb 25, 2012 at 20:41
  • 42
    It's like doing boolean == true: it doesn't make sense. Expressions inside if statements are just that: expressions. If something already evaluates to a boolean expression, why would you add a check to force it to evaluate to that?
    – Maxpm
    Commented Feb 25, 2012 at 20:43
  • 13
    @zzzzBov: Um, no. That's not how most (C-style) programmers do it.
    – amara
    Commented Feb 25, 2012 at 21:04
  • 11
    @zzzzBov: Your comment is ambiguous. If you meant that !boolean_variable is the way most C programmers do it, I agree. Commented Feb 25, 2012 at 23:06
  • 31
    And more importantly, how come nobody wants to write boolean != true?
    – user34530
    Commented Feb 26, 2012 at 0:00

17 Answers 17

172

When I see a line like if (!lateForMeeting()), I read that as "If not late for meeting", which is quite straight-forward to understand, as opposed to if (lateForMeeting() == false) which I'd read as "If the fact that I'm late for meeting is false".

They're identical in meaning, but the former is closer to how the equivalent English sentence would be constructed.

13
  • 29
    +1 In Python you actually write if not late_for_meeting :)
    – phunehehe
    Commented Feb 26, 2012 at 13:04
  • 49
    I contend that if "if ___ is false" sounds more natural than "if not ___", then the name of ___ needs improvement. Commented Feb 26, 2012 at 17:45
  • 13
    In Perl you can write unless late_for_meeting Commented Feb 27, 2012 at 7:21
  • 7
    @HenrikRipa: It seems like just about anything you can type is legal code in Perl. Whether or not it does what you want is another question ;) Commented Feb 27, 2012 at 13:22
  • 5
    @A-Cube I wouldn't have a method like that to begin with. Instead, I'd have a method called done(). Double negatives are bad.
    – kba
    Commented Feb 27, 2012 at 15:34
106

Writing == false and == true is redundant. It can be taken to arbitrary extremes, too. If you start writing

if (condition == false) { ... }

Then why not

if ((condition == false) == true) { ... }

Or why not

if ((someExp == anotherExp) == true) { ... }

The moral of this story is that if condition is a boolean expression, then you don't need to add == false; that's what operator ! is for ;)

7
  • Didn't think of this!
    – ell
    Commented Feb 25, 2012 at 21:40
  • 64
    == false is NOT redundant, just more verbose than !. OTOH, == true is redundant.
    – dan04
    Commented Feb 25, 2012 at 23:44
  • 4
    @dan04 You're right. However, in the sense I meant it, it remains a bad idea. Consider (exp1 != exp2) vs ((exp1 == exp2) == false). Admittedly, these are contrived scenarios, but still you should almost never write explicit comparisons to true or false. Just as you should use operator !=, so you should use !.
    – Andres F.
    Commented Feb 26, 2012 at 4:56
  • 27
    @dan04: It is redundant when the language already offers !.
    – DeadMG
    Commented Feb 26, 2012 at 7:19
  • 6
    @dan04: Any time you write bool_expression == bool_literal, the == ... is redundant. Whether you're testing for true or false is irrelevant. It's just a change in the order of the consequent/alternative blocks. Andres' examples illustrate this point perfectly. Most modern compilers will optimize away the redundancy, but it's still redundant. Commented Feb 27, 2012 at 10:40
86

In C and some similar languages, comparing boolean expressions for equality to false or true is a dangerous habit.

In C any scalar expression (numeric or pointer) can be used in a boolean context, for example as the condition of an if statement. The C rule is that if (cond) is equivalent to if (cond != 0) -- i.e., zero is false, and any non-zero value is true. If cond is of pointer type, 0 is treated as a null pointer constant; if (ptr) means if (ptr != NULL).

This means that

if (cond)

and

if (cond == true)

do not mean the same thing. The first is true if cond is non-zero; the second is true only if it's equal to true, which in C (if you have #include <stdbool.h>) is simply 1.

For example, the isdigit() function declared in <ctype.h> returns an int value: non-zero if the argument is a digit, 0 if it isn't a digit. It can return 42 to indicate that the condition is true. Comparing 42 == true will fail.

It happens that 0 is the only value considered to be false, so comparison for equality to false will work; if (!cond) and if (cond == false) do the same thing. But if you're going to take advantage of that, you have to remember that comparing to false is ok, and comparing to true is not. Worse yet, comparing to true will work most of the time (for example, the equality and relational operators always yield either 0 or 1). This means that any bugs you introduce by using this still could be difficult to track down. (Don't worry, they'll show up as soon as you demo the code to an important client.)

C++ has slightly different rules; for example, its bool type is a bit more tightly integrated into the language, and if (cond) converts cond to type bool. But the effect is (mostly) the same.

Some other languages have what one might call better behaved booleans, such that cond == true and cond == false (or whatever the syntax happens to be) is safe. Even so, every language I've seen has a not or ! operator; it's there, so you might as well use it. Using cond == false rather than !cond or not cond does not, in my opinion, improve readability. (It's true that the ! character can be difficult to see at a glance; I sometimes add a space after the ! to avoid this.)

And often you can avoid the issue and improve clarity by rearranging the code slightly. For example, rather than:

if (!cond) {
    do_this();
}
else {
    do_that();
}

you might write:

if (cond) {
    do_that();
}
else {
    do_this();
}

That's not always better, but it doesn't hurt to look for opportunities where it is.

Summary: In C and C++, equality comparisons to true and false are dangerous, overly verbose, and poor style. In many other languages, such comparisons might not be dangerous, but they're still overly verbose and poor style.

8
  • 1
    +1 for this being the one answer with the actual useful technical explanation.
    – Mike Nakis
    Commented Feb 26, 2012 at 10:19
  • I still think this way, regardless of programming language I always assume that == true is unsafe. Feels better that way.
    – Dervall
    Commented Feb 26, 2012 at 12:06
  • 1
    @Dervall: assuming something that's simply not the case is also no good. There are a few corner cases in certain languages where equality comparison of booleans is not only safe but in fact appropriate, for instance in Haskell, which has a strong implicit-cast-free type system with bidirectional type inference, one might write (==True) . f to clarify that we want the -> Bool instantiation of the return-polymorphic function f. That's clearer than not . not . f and less awkward than (f :: a -> Bool). Commented Feb 27, 2012 at 12:48
  • 1
    @leftaroundabout: That's fine if you know that pred(x) and pred(y) use the same value to denote truth, which is a safe assumption in some languages but not in others. In C, for example, you might write !!pred(x) == !!pred(y). Commented Feb 27, 2012 at 18:36
  • 2
    @KRyan: Equality comparison to false happens to be "safe", since 0 is the only "false" value -- but it's IMHO better to avoid equality comparison to either true or false in general. Commented Nov 30, 2015 at 21:59
18

The two are functionally identical, so which one to use is a matter of taste.

The major reason that I use == false is that I have found that !is too easy to overlook, when looking at code.

Having been bitten severely by this, I've made a habit of making it very clear when testing for false.


Had the operator been named not as in Pascal, I do not think this would have become an issue.

10
  • 9
    For this very reason, a C++ project I worked on for some medical device software had a coding standard which mandated == false instead of ! for this same reason (to make it stand out). However there was no requirement to use == true, so any non-zero value still worked as it should.
    – tcrosley
    Commented Feb 26, 2012 at 0:43
  • 14
    I've always found this argument unconvincing - there are other places in C/C++/C#/Java/etc where failing to see a single character has a similarly significant impact on the interpretation of the code; singling out "!" as the only bad one doesn't make sense to me.
    – Bevan
    Commented Feb 27, 2012 at 8:18
  • 6
    @bevan Apparently you have not been bitten yet.
    – user1249
    Commented Feb 27, 2012 at 11:46
  • 2
    While I agree that overlooking ! is probably the most troublesome mistake of this kind, this should IMO not give rise to making a habit of writing ==false but of writing better unit tests. Commented Feb 27, 2012 at 13:04
  • 8
    @ThorbjørnRavnAndersen Quite the reverse - I've been bitten often enough over the years that I've taught myself to read every character. I'm not the author of all (or even most) of the code I have to read day to day, so any personal convention as we're discussing here has minimal value: I need to correctly understand all the code I read, not just the stuff I've written.
    – Bevan
    Commented Feb 27, 2012 at 18:00
14

If condition == false is indeed “much more natural in English” for you then I must assume that you are not a native speaker. Otherwise I cannot explain this, because nobody speaks like that:

If the sun is shining is false I stay at home.

Compare that to

If the sun is not shining I stay at home.

That said, I agree that the single, slender ! character is easily overlooked in code. For that reason, I prefer the keyword not when supported by the language. C++ for instance does allow this although many programmers are not aware of it.

For languages that require !, I put a space between operator and operand. This makes the negation much harder to overlook:

if (! condition) { … }

Notice that every programmer should translate this automatically, without second thought, to “not condition” in their head. Acquiring this kind of fluency in reading code idioms is among the first steps in becoming a good programmer.

3
  • 2
    the problem with your analogy is that you can't split 'the sun' and 'shining' and insert a not in the middle. correct comparison would be 'if not the sun shining i stay home' which, if you're not yoda, you'd never say in english.
    – controlbox
    Commented Oct 5, 2020 at 9:31
  • @controlbox This isn’t a problem with my analogy. But, like all analogies, it is limited and when you try to take it too far, it breaks. The point of the analogy (and for which is completely sufficient) is that it makes no sense in boolean algebra to add a comparison to a literal. It neither adds clarity nor reads naturally when “translated” into English. Commented Oct 5, 2020 at 9:40
  • Do you happen to know if there's a editorconfig rule for the extra whitespace after ! ?
    – janv8000
    Commented Sep 30, 2022 at 7:07
8

because sometimes you might write boolean = false (with the obvious errors) and false == boolean doesn't seem natural (no matter how good of a practice it is)

2
  • 1
    A long time ago when I first started programming, a mentor of mine suggested I get in the habit of doing if( INVALID_HANDLE_VALUE == hFile ) to avoid things like that. That way if you slip up and use one equals sign instead of two, you'll get a compiler error. Obviously this only works when the left-expression is a constant, but it has saved me more head-aches than I can count. Commented Feb 26, 2012 at 3:07
  • if you use a static analysis tool, it would save you hundred times more head-aches, and you are able to restore the nature hFile==INVALID_HANDLE_VALUE writing.
    – Gqqnbig
    Commented Jul 10, 2018 at 23:04
7

When I see var == false I always wonder whether var is boolean or of a logic type with more than two values (with, for example, a maybe and an undefined as well as true and false, or something like the nine values of IEEE 1164).

1
4

if (!boolean_variable) translates to if the condition is not true.

if (boolean == false) translates to if the condition not false is true. Because that is inversed logic, it is harder to understand.

3
  • 3
    !true means not true. !boolean means either not false or not true depending on the value of the boolean, which itself is logical inversion.
    – S.Robins
    Commented Feb 26, 2012 at 0:53
  • 1
    @S.Robins I find stupid name of boolean for a boolean variable. Something like for example isVisible would be a better example. Then if (!isVisible) would mean if not visible - which is simpler to understand then if (isVisible==false), which is an inverse logic. Hope it's clearer now. Or, did I misunderstood your comment? Commented Feb 26, 2012 at 1:02
  • you are inserting the 'not' where it can't actually go to suit your argument. your first example translates to 'if not the condition is true'.
    – controlbox
    Commented Oct 5, 2020 at 9:37
3

In (much) older compilers, I believe they would break (boolean == false) into 2 register assignments and a compare code in machine language. The first example would be broken into one assignment and a NOT operator. In terms of performance, the compare operation would take a number of clock cycles, depending on the size of the register being compared, compared to a bitwise invert (1 clock) and would be slower to execute.

That being said, I believe newer compilers do away with this, so it should be OK to go with either.

2
  • Generating machine code is the compiler's job, not the high-level-language programmer's...
    – user
    Commented Feb 27, 2012 at 9:34
  • For historical reasons, this may very well be one of the reasons one method became preferred over the other.
    – Legolas
    Commented Feb 27, 2012 at 13:43
1

When you're testing the true condition, it makes sense to do just if (condition), especially when you apply the convention of naming boolean variables beginning with 'is': if (isOpen) is perfectly clear and using != false would be redundant.

For a C/C++/Java/etc. programmer, the meaning of the '!' operator is completely assimilated, to the point that we automatically have 'not' in our minds when we see it. So having if (!isOpen) is as clear as if (_NOT_ isOpen) for me. But you're not familiar enough, in C/C++ you could create a macro with #define _NOT_ !. But trust me, after a few years this is completely unnecessary.

Aside that, it's always preferable to test boolean values without comparing them with literals. For instance, it's dangerous to test if (x == true) because a boolean value is considered true if it's not zero, and the literal true has just one specific value, so x could be 'true' (i.e. nonzero) and still the comparision evaluate to false (because it contains 2 and the literal true is, say, 1.) Of course that doesn't apply to a comparision with false, but if you don't use it when testing for true, why use it when testing for false?

2
0

Size matters ;)

In mixed expressions it is easier to read:

boolean1 = false
boolean2 = true

p ! boolean1 and ! boolean2
p boolean1 == false and boolean2 == false

And especial for ruby an example where it is a big difference:

boolean = nil
p ! boolean         #-> true
p boolean == false  #-> false

nil is not false, but it is also not true.

0

Based from my experience and the answers from my quesion that you have linked to.

Some people prefer to use if(condition), for the reason is that one it is shorter to write. and for me it actually makes sense, for example (! isValidated()) I read this as Not Validated. but for me it's all based on personal preferences, and it depends on the logical structure of isValidated() method, if it either returns true or false

1
  • I don't think it should be based on personal preference; it should be based on the understanding of the nitty gritty details of the programming language you use. Explicitly comparing against true or TRUE in C or C++ can generate invalid code. For example: if (binary_value & BITMASK)) can be used to check if any of the bits in BITMASK are set in the binary_value variable. But if you write if ((binary_value & BITMASK) == TRUE) then the expression will work only for the bit in the TRUE value, and it's not the intent.
    – PRouleau
    Commented Jul 23, 2023 at 18:59
0

If you named your variable properly, then !boolean is more natural. It reads as not boolean to anyone who's enough of a programmer to read code mentally.

0

For some folks, the sooner a meaning is expressed the better.

For those folks having "if ! ..." compares faster to "if ..." then having to read through the entire condition (which could actually be pretty long, e.g. (thisThing = thatThing or something = the other thing) OR (thinga = thingb and thinga = thingd), etc.) just to find the ==false at the end.

Having the ! (I actually prefer a not when the language allows it) right up front gets the english 'not' for this condition in there sooner.

This issue also leads to consideration for using until in languages that support it, e.g. do 'common stuff' until thing completes. As others say, natural language expression is the goal. I like the "sun is shining" example above.

0

Another reason is that if you are working in a codebase that uses several languages, if there's one idiomatic way to do something that's safe in all of the languages, it's a pretty good idea to do it that way everywhere so that you form a good habit and are less likely to trip up.

I can't think of anywhere that if (!variable) (or equivalents such as if not variable depending on your language) is not safe, whereas e.g. if self.is_ready() == False: ... is not safe in python if self.is_ready() returns None, now or in the future, which would be a totally reasonable thing for it to do to indicate it wasn't ready since None is just as falsey as False.

0

At work I often am dealing with Booleans which can be null so I'll often code this case as

if (value != null && value == true) {
        //do something
}

because I personally feel the symmetry makes it easier to read. Especially if there are other Booleans being tested as well.

I don't really care one way or the other.

9
  • 5
    if value == true then there's no reason to check that it's not null. If the value == null it should never trigger the if statement in the first place, so if (value) should be sufficient.
    – zzzzBov
    Commented Feb 25, 2012 at 22:27
  • 2
    Booleans are objects (in java) and can therefore be null so just saying if (value) throws an exception. I'd appreciate it if people who downvote give a reason.
    – WuHoUnited
    Commented Feb 26, 2012 at 4:16
  • 3
    I just happen to see this, didnt downvote. Boolean null is not good practice. Why? because boolean usually represents a state of something turned on on off. In most cases you would want to declare it false at the beginning and then change it along with behaviour. It is very uncommon to see boolean not being initialised.
    – Aubergine
    Commented Feb 26, 2012 at 5:18
  • I have to agree with Aubergine here, I myself have fallen into the bad habit (especially in Java) of leaving bools uninitialized and then end up checking for null. I think this is more of a flaw of the language, however which imposes that flaw on the user. When declaring a new bool variable it should default to false without initialization in my opinion.
    – user22018
    Commented Feb 26, 2012 at 11:39
  • 2
    @WuHoUnited, even if the value was null, value == true would be sufficient.
    – zzzzBov
    Commented Feb 27, 2012 at 4:49
0

In newer languages, like Swift, you have “optional” types, including “optional bool”. An optional bool has values false, true, or nil. In that case, an explicit comparison gives exactly what you ask for. x == false tells you x is false, not true or nil. x != true tells you that x is not true, but either false or nil.

So in Swift, x == false would catch attention, because I will automatically assume that x might be nil.

Not the answer you're looking for? Browse other questions tagged or ask your own question.