Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

A comment on this question: Calling A Method that returns a boolean value inside a conditional statement 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?

share|improve this question
23  
It is shorter to write. –  Zenon Feb 25 '12 at 20:41
31  
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 Feb 25 '12 at 20:43
7  
@zzzzBov: Um, no. That's not how most (C-style) programmers do it. –  sparkleshy Feb 25 '12 at 21:04
5  
@zzzzBov: Your comment is ambiguous. If you meant that !boolean_variable is the way most C programmers do it, I agree. –  Keith Thompson Feb 25 '12 at 23:06
19  
And more importantly, how come nobody wants to write boolean != true? –  todofixthis Feb 26 '12 at 0:00

17 Answers 17

up vote 124 down vote accepted

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.

share|improve this answer
17  
+1 In Python you actually write if not late_for_meeting :) –  phunehehe Feb 26 '12 at 13:04
27  
I contend that if "if ___ is false" sounds more natural than "if not ___", then the name of ___ needs improvement. –  Mike DeSimone Feb 26 '12 at 17:45
9  
In Perl you can write unless late_for_meeting –  Henrik Ripa Feb 27 '12 at 7:21
3  
@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 ;) –  Adam Robinson Feb 27 '12 at 13:22
3  
@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 Feb 27 '12 at 15:34

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.

share|improve this answer
2  
!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 Feb 26 '12 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? –  BЈовић Feb 26 '12 at 1:02

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)

share|improve this answer

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.

share|improve this answer
3  
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 Feb 25 '12 at 22:27
1  
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 Feb 26 '12 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 Feb 26 '12 at 5:18
1  
@WuHoUnited, even if the value was null, value == true would be sufficient. –  zzzzBov Feb 27 '12 at 4:49

It is just the matter of style. !boolean is more confusing to me.

In Software-Engineering-I class we were taught to write code that is much clearer and much more readable. Few months later when you see your code and find !boolean you might not see ! when going through the code. But if you see boolean == false, it will make much more sense.

I can say that code bool working = true; if (working == false) is much more readable than if (!working)

. Both can be applied and both are correct. If I had to choose I would choose code that is more readable and easy to understand.

I got GPA of 4.0 in Software-Engineering-I class.

share|improve this answer
5  
Your GPA is irrelevant to the discussion. Your point about readability has some validity but can easily be disarmed by putting a space between operator and operand: if (! condition) or by using the appropriate keyword in languages which support that: if (not condition). –  Konrad Rudolph Feb 26 '12 at 15:05
1  
How does one develop a GPA for a single class? –  Adam Robinson Feb 27 '12 at 13:39

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 ;)

share|improve this answer
41  
== false is NOT redundant, just more verbose than !. OTOH, == true is redundant. –  dan04 Feb 25 '12 at 23:44
3  
@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. Feb 26 '12 at 4:56
21  
@dan04: It is redundant when the language already offers !. –  DeadMG Feb 26 '12 at 7:19
3  
@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. –  Lèse majesté Feb 27 '12 at 10:40

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).

share|improve this answer
6  
The 3rd value is usually "File not found". thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx –  Groky Feb 26 '12 at 1:29

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.

share|improve this answer
4  
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 Feb 26 '12 at 0:43
6  
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 Feb 27 '12 at 8:18
3  
@bevan Apparently you have not been bitten yet. –  user1249 Feb 27 '12 at 11:46
3  
@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 Feb 27 '12 at 18:00

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.

share|improve this answer

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?

share|improve this answer

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, 0 if the argument is a digit, non-zero if it isn't. 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.

share|improve this answer
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). –  leftaroundabout Feb 27 '12 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). –  Keith Thompson Feb 27 '12 at 18:36

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.

share|improve this answer

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

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

For precisely the same reason that one doesn’t (normally) query “Is it false that it is time to get up?” It is periphrasic.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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