Followers 0

# How to use bool variable.

## 47 posts in this topic

I think if you are disciplined enough to remember to put the constant first, you are also disciplined enough to use the correct operator.
The problem isn't remembering, the problem is an accidental typo that gets overlooked. Sometimes you try to double-tap '=' but only one registers (maybe you accidentally pressed too softly the second time, or something). It's happened to me before (albeit very rarely).

A much better solution is to set up your compiler so it will warn you if you write an assignment where you probably meant to write a condition.
I agree, though I believe this style started before compilers warned of such things (I could be wrong on this, but it seems probable), and it's just stuck (perhaps to keep a consistent coding style). Yeah, we live in a modern age with decent compilers, but relying on that warning doesn't guard against everything:

// Compiling with LLVM from http://llvm.org/demo/index.cgi
int a = 1;
bool b = a = 42; // It doesn't catch this

if (a = 0) // But it catches this
{
b = false;
}


FWIW, I'm not advocating this use; I'm merely playing devil's advocate and saying it's not entirely useless. If you're writing a code base where a single bug can be catastrophic (like a missile/rocket guidance system, or robotic surgical system, or something), these "extra precautions" just might be worth it.

Use a modern compiler and it will warn you on such issues.

test.cc:5:7: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(a = false)
~~^~~~~~~
test.cc:5:7: note: place parentheses around the assignment to silence this warning
if(a = false)
^
(        )
test.cc:5:7: note: use '==' to turn this assignment into an equality comparison
if(a = false)
^
==


Edited by Washu
0

##### Share on other sites

Use a modern compiler and it will warn you on such issues.

test.cc:5:7: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(a = false)
~~^~~~~~~
test.cc:5:7: note: place parentheses around the assignment to silence this warning
if(a = false)
^
(        )
test.cc:5:7: note: use '==' to turn this assignment into an equality comparison
if(a = false)
^
==

Huh? I did use a modern compiler... I used LLVM, and just like you (and I) posted, it warns about the if statement on line 5, but not about the assignment on line 3 (which was the whole point of that code snippet)...

0

##### Share on other sites

if(a = true)

in visual studio 2005,there is no warning no error.

0

##### Share on other sites
if(a = true)

in visual studio 2005,there is no warning no error.

You may have to set the warning level to /W4. At least I know you do on 2010. However, this can be annoying, as some 3rd party libraries may produce a lot of warnings on /W4.

Edited by Cornstalks
0

##### Share on other sites

Use a modern compiler and it will warn you on such issues.

test.cc:5:7: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(a = false)
~~^~~~~~~
test.cc:5:7: note: place parentheses around the assignment to silence this warning
if(a = false)
^
(        )
test.cc:5:7: note: use '==' to turn this assignment into an equality comparison
if(a = false)
^
==

Huh? I did use a modern compiler... I used LLVM, and just like you (and I) posted, it warns about the if statement on line 5, but not about the assignment on line 3 (which was the whole point of that code snippet)...

That's because that assignment has valid uses and coding in an exception for that case would be less productive.

0

##### Share on other sites

yes.if set the warning level to /W4.there will be warning.

Edited by xiajia
1

##### Share on other sites
That's because that assignment has valid uses and coding in an exception for that case would be less productive.

Sure, it's valid, but it's just as (technically) valid as the expression in the if statement. My point was that you can't totally rely on the compiler to warn you if you accidentally make the typo someVar = 42 instead of someVar == 42, and if instead you did 42 == someVar (and then your typo was 42 = someVar), at least you would catch it at compile time. Álvaro's point is good in that the compiler should warn you, but I'm suggesting you can't totally rely on that. My point isn't whether or not the compiler should warn you. Also, I'm not saying one should put the read-only value on the left and the variable on the right; I'm merely pointing out that there is at least some justification for those who choose to do so. I personally don't, but I was originally responding to a post that said "You truly gain nothing from that" which is not quite the case; you gain something, albeit a very small something (but again, that small something may be significant to you or your company's standards).

0

##### Share on other sites
yes if set the warning level to /W4.there will warning.

Scary. Maybe you should upgrade to a newer VS. I've been using 2008 and it warns about assignments as conditions unless they're placed in braces.

0

##### Share on other sites

If you turn the warning level in VS 2010 to level 4, it warns "warning C4706: assignment within conditional expression".

0

##### Share on other sites

In my opinion, using an actual comparison in a conditional clause is more readable than using a Boolean expression without one.

if(ReturnsABool() == false) {...}   /* is better than */   if(!ReturnsABool()) {...}

Your sentence should more correctly read 'using an actual boolean-valued comparison expression in a conditional is more readable than using a boolean-valued expression without one.  I don't believe this is true, but I believe parsimony is a virtue and one should eschew the obfuscation of unnecessary verbosity and redundancy.

Also, testing a Boolean expression for equality is more readable than testing it for inequality.

if(ReturnsABool() == false) {...}  /* is better than */  if(ReturnsABool() != true) {...}

I would phrase that as "positive logic is easier to reason about than negative logic."  Alternatively, you could say that it is not easier to reason about negative logic.

Along the same lines, I prefer to pass enumerated values as parameters over integers or Boolean values.

car Car(car::RED);  /* is better than */  car Car(0x02);  /* or */  car Car(true);

This.  Every time.

However, there is a place for well-named boolean variables and functions.  Their use in control structures contribute greatly to the readabilty of code.

If find this

while (thread.is_running())
{
// ...
}


quite an improvement over

while (thread.is_running() == true)
{
// ...
}

Try reading them both aloud to see which one makes more sense.

0

##### Share on other sites

May be the one who gave the advice was thinking of another language, not C++.

For example in Lua this advice can make sense, because "if myBool then" returns true if myBool is assigned any value other than nil or false; while "if myBool == true" will only run if myBool is actually true.

On the other hand "if not myBool" is not the same as "if myBool == false", because the former will test if myBool is either nil (non existent) or false. While the latter will only work if myBool has been explicitly assigned the value "false".

This is a common issue in most dynamically typed languages like Python or Lua.

But in C++ the advice makes little sense, and personally I would suggest "if( myBool )" for all the reasons already stated so far.

0

##### Share on other sites

if(a) ===> if (a) is true, do the following

if(a==true) ===> if (if (a) is equal to true) is true, do the following

This first one is clear (especially if your variable is properly named), concise, easy to write and easy to read.  The second is redundant.

You should use the first in most cases.  I'd consider using the second case if the variable, or function, is named in such a way that explicitly adding the "== true" or "== false" actually helps readability, which IMO does sometimes happen.

0

##### Share on other sites

Using stock warning level in Visual Studio 2012, if I use an assignment operator in the if statement it does not produce a warning and compiles just fine.  No complaints from Visual Studio

I actually was programming at about 3 in the morning the other day and made this mistake.  Compiler never did warn me and when I went to test it out of course a bug was produced.  Though the debugger basically told me what it was because it would end up being an index out of bounds.  So the debugger pointed to that line and I immediately saw the mistake of using the assignment operator.  I did feel like a complete rookie again.

Though the point just goes on that using stock Visual Studio Warning levels will not produce a warning for it.  I would not say it'd be safe to rely on the compiler to warn you about it.

0

##### Share on other sites
Never understood this if(false == a) stuff. I compare one variable to another as often if not more often than I compare a variable to a constant. Since I'll just create a strange bug if I get the operator wrong in a variable to variable case, what's the advantage of a "trick" that makes code less readable and encourages me to stop paying attention to quite an important C++ subtlety?

Often getting it wrong and suffering the consequences in my early days of C++ was the best way for me to avoid this typo, along with compiler warnings. Edited by Aardvajk
0

##### Share on other sites
Hey Cornstalks,
You might want to put a name to the practice of putting the variable last in a comparison. They're "Yoda conditions".
http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html

Ha, thanks for that. There are some pretty good ones there.

0

##### Share on other sites

Quite frankly I see the use of if(whatever == true) as redundant code since it is almost common knowledge in coding that if(whatever) and if(whatever == true) are synonymous just as if(!whatever) and if(whatever == false) are synonymous. This really shouldn't matter in regards to true boolean logic as we are talking about coding standard, in real world application things like defining 1 to be true and 0 to be false with defines(like in C++) are just as stylistic as anything else.

if people really want to use the lengthier version that is up to them, but it is literally just that, longer.

The point of the code is for it to do what you -think- it does, not to do what a real world definition says it should, it is a loose standard not a limiting factor. Quite frankly if you're using truth tests in your code and set the value to 2 or 3 and are surprised it results in true then your logic for setting it to that number in the first place seems flawed.

The one place I would agree the syntax is silly is if(for some odd reason) someone did something like int whatever = 17, if(whatever) as opposed to some sort of greater than or equal equality test, but who codes like that?

Edited by Satharis
0

##### Share on other sites
in real world application things like defining 1 to be true and 0 to be false with defines(like in C++) are just as stylistic as anything else.

Uhm, true and false aren't defines in C++, because they aren't something that is just commonly tagged on like in C. That's actually making a very big difference, because in C a BOOL(EAN) is typically defined as int, while in C++ it is an actual type.

BOOLEAN b = 5;

if (b == TRUE)

is going to fail. Best example of that I found in the source of a certain game. Some genius decided to return "2" from a BOOLEAN function, because he needed a third result. Of course he didn't bother changing the function to int or some meaningful enum. Even less did that person bother to check all places where that function was already used. So other code that explicitly compared to "TRUE" was now broken.

So in C I would actually very much advice _against_ making explicit comparisons for the very reason that it's just defines (so to be safe, you would always have to either compare against FALSE or use some ridiculous trick like "if (!!variable == TRUE)").

Now, in C++

int x = 5;

if (x == true)

should work just fine (unless I'm getting my promotions wrong), because x will implicitly be turned into an actual bool of value "true". The compiler hopefully still slaps you with some kind of warning for doing this, though.

Still, just because explicit comparisons with "true" are "safe" in C++ doesn't make them any less pointless and redundant to me. The only argument I consider somewhat valid is that a "!" can easily be missed when browsing code, while "== false" is clunky enough to be noticed.

1

##### Share on other sites

read so many doscussions,I am even more confused.....

if(a) ? or if(a == true)? or all ok?

0

##### Share on other sites
read so many doscussions,I am even more confused.....

if(a) ? or if(a == true)? or all ok?

Either one is ok, but if(a) is usually slightly preferred as a matter of personal preferences.

0

##### Share on other sites
Now, in C++

int x = 5;

if (x == true)

should work just fine (unless I'm getting my promotions wrong), because x will implicitly be turned into an actual bool of value "true". The compiler hopefully still slaps you with some kind of warning for doing this, though.

You are getting your promotions wrong. `true' will be promoted to int with a value of 1 and the condition will be false.
2

##### Share on other sites

Well, at least it's a good example why I never blindly rely on promotion rules and operator precedence. Also another (questionable) argument for not using "== true", at least if you're in the annoying habit of being sloppy with your variable types (the next time I see an unsigned short used in "if (v == -1)" I might have to scream).

0

## Create an account

Register a new account