views:

1240

answers:

17

Hey.

I was coding here the other day, writing a couple of if statements with integers that are always either zero or one. I asked myself:

Should test against 1 or 0?

For example, given an int n, if I want to test if it's "true", should I use n == 1 or n != 0?

Is there any difference at all?

Please don't answer with stuff regarding the int may being more/less than 1/0, that's not what I want to know.

+42  A: 

Human's brain better process statements that don't contain negations, which makes "int == 1" better way.

Luno
Or humans can better process statements that are positives.
Mark Byers
+1 for Mark Byers ;) I wrote it deliberately
Luno
You couldn't say that humans don't prefer not using not few negations. Wait, or was it the opposite? :-)
Francesco
Human's brain? What about computer's brain?
Emil
Haven't you moved to thinking binary, yet?
Simpzon
@Emil, it's also important that your code communicates with other humans (other programmers and even yourself, months or years later).
CPerkins
-1 for `don't contain negations`, my brain can't process that *(I did not actually give you a -1 :)*
BlueRaja - Danny Pflughoeft
17 upvotes for a joke answer?
Joren
It's not a joke answer, and it's actually a very good point.
fearofawhackplanet
In my honest opinion, getting used to reading if (!expr) as if not expression; is probably the single hardest thing you need to learn when picking up a language like C. Especially if you have a crappy font.
TerryP
@Emil: Who cares about computer understanding? If you're picking between two identical ways of writing something, you pick the one humans will do better with.
David Thornley
Tuple negation is considered improper in English for a reason :)
SnOrfus
+33  A: 

It really depends. If you're using a language that supports booleans, you should use the boolean, not an integer, ie:

if (value == false)

or

if (value == true)

That being said, with real boolean types, it's perfectly valid (and typically nicer) to just write:

if (!value)

or

if (value)

There is really very little reason in most modern languages to ever use an integer for a boolean operation.

That being said, if you're using a language which does not support booleans directly, the best option here really depends on how you're defining true and false. Often, false is 0, and true is anything other than 0. In that situation, using if (i == 0) (for false check) and if (i != 0) for true checking.

If you're guaranteed that 0 and 1 are the only two values, I'd probably use if (i == 1) since a negation is more complex, and more likely to lead to maintenance bugs.

Reed Copsey
Objective-C supports booleans, right? I'm having some trouble with NSLogging booleans, that's why I'm using an int. (irrelevant to question)
Emil
@Emil: Objective-C, like C, does not contain a "real" boolean type, but has a macro defining it (to YES and NO instead of TRUE/FALSE). For details, see: http://iphonedevelopertips.com/objective-c/of-bool-and-yes.html
Reed Copsey
Whatever is the point of `if (false)`? it'll never execute its statements. And `if (true)` will always execute its statements.
Joren
I would just add in addition to the excellent advice of Reed Copsey, being consistent across the codebase helps (write it down in a HACKING file or sth for the next sap^H^H^Hcoder).
TerryP
@Joren: That look better? I was just suggesting using false or true instead of 0/1...
Reed Copsey
I don't like tests with boolean vars compared to the constants the way you did this. I prefer to name my boolean variables with 'is', such as isFileOpen. My test would be "if (isFileOpen)", not the cumbersome "if (isFileOpen == true)".
aaaa bbbb
@aaaa bbbb: I often do that, but, in this case, the goal was to suggest using booleans instead of using integers. The same can be done with int values (in C and Objective-C, not C#, though), but it is more clear when you're being explicit with booleans.
Reed Copsey
`== false` of `== true` or `== true == true == true` is nonsense. Just write `if (!value) {`/`if (value) {` (adjust syntax and formatting to context).
Tom Hawtin - tackline
Noooo! What Tom Hawtin said.
JeremyP
@Reed Copsey Objective-C like C(99) which it is a superset of *does* contain a real boolean type.
JeremyP
-1 If you use a language that supports booleans you should write `if(value) ...` or `if (!value) ...`.
starblue
@JeremyP: Objective-C does not, in it's standard implementation. Some vendors have added one, but it's typically a define in NSObject.h. For details, see: http://www.otierney.net/objective-c.html
Reed Copsey
@starblue: As I mentioned before, I typically do that, but I wanted to illustrate testing the value against a boolean and not an integer. I'll try to rework my answer to make this even more clear.
Reed Copsey
@Reed Copsey. Objective-C is a **strict superset of C99**. C99 has a boolean type. Therefore Objective-C has a boolean type.
JeremyP
@JeremyP: Very untrue. If you don't believe me, here's Apple's official reference, showing that BOOL is a typedef for (signed) char, and YES/NO are typedefs: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/doc/constant_group/Boolean_Values
Reed Copsey
@JeremyP: Objective-C is a strict superset of C89 - It was developed in 1996, and predates C-99, which was ratified in 2000 (though it does share most C99 features now).
Reed Copsey
@Reed Copsey: Objective-C as compiled by the current toolchain is a strict superset of C99. C99 has a boolean data type called _Bool therefore Objective-C has a boolean data type called _Bool. The BOOL type also exists but is a separate typedef'd type that is part of the Objective-C run time (so you could argue it too is part of the language).
JeremyP
@Reed Copsey: By the way, this is the releavant reference for BOOL http://developer.apple.com/mac/library/documentation/cocoa/reference/objcruntimeref/Reference/reference.html#//apple_ref/doc/uid/TP40001418-CH3g-SW4
JeremyP
@JeremyP: My issue in saying it's not a "real" type is that, in objective-C, you can assign 2 to a BOOL value **without error**, which means that BOOL is not YES or NO anymore. See the "Special Considerations" section in there....
Reed Copsey
@Reed: I'm not disputing that BOOL is not a real boolean type, I'm disputing your assertion that Objective-C does not have a boolean type. It does. It has the C99 _Bool type.
JeremyP
(And _Bool becomes bool with <stdbool.h>.)
Roger Pate
@Reed: LOL. If I found someone coding the text `if (var == false)`, that person would be marked with attribute "never pay for their work."
Heath Hunnicutt
+2  A: 

If only two values are possible, then I would use the first:

if(int == 1)

because it is more explicit. If there were no constraint on the values, I would think otherwise.

Justin Niessner
A: 

(Assuming your ints can only be 1 or 0) The two statements are logically equivalent. I'd recommend using the == syntax though because I think it's clearer to most people when you don't introduce unnecessary negations.

Stuart
+1  A: 

When using integers as booleans, I prefer to interpret them as follows: false = 0, true = non-zero.

I would write the condition statements as int == 0 and int != 0.

CodeSavvyGeek
+5  A: 

A Daft question really. If you're testing for 1, test for 1, if you're testing for zero, test for zero.

The addition of an else statement can make the choice can seem arbitrary. I'd choose which makes the most sense, or has more contextual significance, default or 'natural' behaviour suggested by expected frequency of occurrence for example.

This choice between int == 0 and int != 1 may very well boil down to subjective evaluations which probably aren't worth worrying about.

James Morris
Not going to -1, because the first two points are quite valid, but calling it a daft question is a bit much. Also, code clarity/readability can be very subjective, but I wouldn't call it "not worth worrying about."
Tanzelax
The last paragraph should be read as a sub clause of the second paragraph, that sometimes any benefits for readability can become so insignificant that it becomes a waste of time worrying about if you should test for `(int == 1) or `(int != 0)`, the phrase "the devil is in the details" comes to mind.
James Morris
+10  A: 

If you're working with values that can only be 1 or 0, then I suggest you use boolean values to begin with and then just do if (bool) or if (!bool).

JAB
+9  A: 

In language where int that are not 0 represents the boolean value 'true', and 0 'false', like C, I will tend to use if (int != 0) because it represents the same meaning as if (int) whereas int == 1 represents more the integer value being equal to 1 rather than the boolean true. It may be just me though. In languages that support the boolean type, always use it rather than ints.

Julien Lebosquain
+3  A: 

To be honest if the value of int is just 1 or 0 you could even say:

if (int)

and that would be the same as saying

if (int != 0)

but you probably would want to use

if (int == 1)

because not zero would potentially let the answer be something other than 1 even though you said not to worry about it.

GEShafer
+1  A: 

I would say it depends on the semantics, if you condition means

while ( ! abort ) negation is ok.

if ( quit ) break; would be also ok.

stacker
+1  A: 
IF INT IS 1
NEXT SENTENCE
ELSE MOVE "INT IS NOT ONE" TO MESSAGE.
FastAl
Which langauge is this?
Emil
http://lolco.de :P
Tobias
+5  A: 

Two points:

1) As noted above, being more explicit is a win. If you add something to an empty list you not only want its size to be not zero, but you also want it to be explicitly 1.

2) You may want to do (1 == int) That way if you forget an = you'll end up with a compile error rather than a debugging session.

Paul Rubel
Nobody else said it, so I'll give my vote here. +1 do ( const/final == var) That way if you forget an = you'll end up with a compile error rather than a debugging session.
Greg Domjan
+1  A: 
if( is_numeric( $int ) ) { its a number }
elseif( !$int ) { $int is not set or false }
else { its set but its not a number }

end of discussion :P

Tobias
Yeah, how 'bout complicating it even more? Haha. :)
Emil
hey, dont blame the messanger :P
Tobias
+1  A: 

I agree with what most people have said in this post. It's much more efficient to use boolean values if you have one of two distinct possibilities. It also makes the code a lot easier to read and interpret.

if(bool) { ... }

Enmanuel Rivera
A: 

I was from the c world. At first I don't understand much about objective-c. After some while, I prefer something like:

if (int == YES)

or

if (int == NO)

in c, i.e.:

if (int == true)
if (int == false)

these days, I use varchar instead of integer as table keys too, e.g.

 name   marital_status
------  --------------
 john      single
 joe       married

is a lot better than:

 name   marital_status
------  --------------
 john         S
 joe          M

or

 name   marital_status
------  --------------
 john         1
 joe          2
ohho
@Horace: But then you run into the issue that ints are handled much better in databases then varchars. It's better to use say a `tinyint(1)` with various values.
Josh K
"these days, I use varchar instead of integer as table keys too" Some will call it bravery
TBH
+1  A: 

As others have said, using == is frequently easier to read than using !=.

That said, most processors have a specific compare-to-zero operation. It depends on the specific compiler, processor, et cetera, but there may be an almost immeasurably small speed benefit to using != 0 over == 1 as a result.

Most languages will let you use if (int) and if (!int), though, which is both more readable and get you that minuscule speed bonus.

me_and
+1  A: 

I'm paranoid. If a value is either 0 or 1 then it might be 2. May be not today, may be not tomorrow, but some maintenance programmer is going to do something weird in a subclass. Sometimes I make mistakes myself [shh, don't tell my employer]. So, make the code say tell me that the value is either 0 or 1, otherwise it cries to mummy.

if (i == 0) {
    ... 0 stuff ...
} else if (i == 1) {
    ... 1 stuff ...
} else {
    throw new Error();
}

(You might prefer switch - I find its syntax in curly brace language too heavy.)

Tom Hawtin - tackline
*Read the question!* "Please, don't answer with stuff regarding the int may being more/less than 1/0, that's not what I want to know."
Emil
@Emil It's what you need to know.
Tom Hawtin - tackline
+1 for mentioning that ints aren't restricted to 0 or 1
mikek3332002