Jump to content

  • Log In with Google      Sign In   
  • Create Account

How to use bool variable.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
47 replies to this topic

#21 VReality   Members   -  Reputation: 436

Like
0Likes
Like

Posted 24 December 2012 - 04:45 PM

A comparison is more explicit than an expression which implicitly converts to bool.  In my opinion this enhances readability.

/* I like */ if(pObject != nullptr) {...}   /* better than */   if(pObject) {...}


Also, when possible, I prefer testing for equality to testing for inequality.

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


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

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


There's plenty of benefit to maximizing readability.



Sponsor:

#22 Álvaro   Crossbones+   -  Reputation: 13317

Like
5Likes
Like

Posted 24 December 2012 - 04:52 PM

I know we all have our pet peeves, but I just don't care if you use `!' or `== false' or `!= true'. Don't sweat the small stuff.

#23 Sik_the_hedgehog   Crossbones+   -  Reputation: 1747

Like
0Likes
Like

Posted 24 December 2012 - 07:32 PM

It is mainly stylistic, though as others have mentioned there is actually a subtle difference between the two, as a boolean variable can actually have values other than true or false.

 

Not in C++. The standard requires that if the bool variable has any non-zero value it has to be treated as true (bool variables only become 0 and 1 when casting to int or float), at least if I'm understanding right.

 

In C this is more tricky since generally bool isn't a built-in type but a typedef to some integer, and in that case yes, they can have any values other than false or true. But the thread title explicitly states C++.


Don't pay much attention to "the hedgehog" in my nick, it's just because "Sik" was already taken =/ By the way, Sik is pronounced like seek, not like sick.

#24 xiajia   Members   -  Reputation: 163

Like
0Likes
Like

Posted 24 December 2012 - 08:51 PM

 

 



 

bool a;
bool b;
bool fa();
bool fb();
if(a)    //instead: if(a == true)
{
    //do true
}
if(!a)    //instead: if(a == false)
{
    //do false
}
if((a && b) || (!a && !b)) //instead: if(a == b)
{
    //do same
}
if(!((a && b) || (!a && !b)))  //instead: if(a != b)
{
    //do different
}
if(!((fa() && fb()) || (!fa() && !fb()))) //instead:  if(fa() != fb())
{
    //do something
}



I think it would be too complicated.


Edited by xiajia, 24 December 2012 - 11:38 PM.


#25 xiajia   Members   -  Reputation: 163

Like
0Likes
Like

Posted 24 December 2012 - 09:11 PM

I think that 'bool' can be described as
 

 

 

enum bool_state
{ 
    BS_FALSE = 0, 
    BS_TRUE = 1
};

 

then code like this:
 

 

 

bool_state flag = 2; //Compilation error

 

code like this:
 

 

 

bool_state flag;
if(flag == BS_TRUE) //runtime error
{ 
//do true
}

 

If you want to express
 

 

 

bool_state flag = (a == b);

 

Use the following method to replace:
 

 

 

if(a == b)
{ 
    flag = BS_TRUE;
}else
{ 
    flag = BS_FALSE;
}

Edited by xiajia, 24 December 2012 - 09:20 PM.


#26 Washu   Senior Moderators   -  Reputation: 5189

Like
0Likes
Like

Posted 24 December 2012 - 09:16 PM

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, 24 December 2012 - 09:19 PM.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
ScapeCode - Blog | SlimDX


#27 Cornstalks   Crossbones+   -  Reputation: 6990

Like
0Likes
Like

Posted 24 December 2012 - 09:22 PM

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)
             ^
             ==

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


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#28 xiajia   Members   -  Reputation: 163

Like
0Likes
Like

Posted 24 December 2012 - 09:34 PM

if(a = true)

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



#29 Cornstalks   Crossbones+   -  Reputation: 6990

Like
0Likes
Like

Posted 24 December 2012 - 09:41 PM

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, 24 December 2012 - 09:42 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#30 Washu   Senior Moderators   -  Reputation: 5189

Like
0Likes
Like

Posted 24 December 2012 - 09:46 PM

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)
             ^
             ==

wacko.png 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.


In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
ScapeCode - Blog | SlimDX


#31 xiajia   Members   -  Reputation: 163

Like
1Likes
Like

Posted 24 December 2012 - 09:50 PM

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


Edited by xiajia, 24 December 2012 - 10:33 PM.


#32 Cornstalks   Crossbones+   -  Reputation: 6990

Like
0Likes
Like

Posted 24 December 2012 - 09:53 PM

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


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#33 Khatharr   Crossbones+   -  Reputation: 3002

Like
0Likes
Like

Posted 24 December 2012 - 10:22 PM

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.


void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#34 MarkS   Prime Members   -  Reputation: 882

Like
0Likes
Like

Posted 24 December 2012 - 10:25 PM

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

 


#35 Bregma   Crossbones+   -  Reputation: 5133

Like
0Likes
Like

Posted 24 December 2012 - 10:47 PM

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.


 


Stephen M. Webb
Professional Free Software Developer

#36 Matias Goldberg   Crossbones+   -  Reputation: 3398

Like
0Likes
Like

Posted 25 December 2012 - 12:39 AM

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.



#37 0r0d   Members   -  Reputation: 819

Like
0Likes
Like

Posted 25 December 2012 - 01:51 AM

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.



#38 Chad Smith   Members   -  Reputation: 1133

Like
0Likes
Like

Posted 25 December 2012 - 05:54 PM

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.



#39 Aardvajk   Crossbones+   -  Reputation: 5982

Like
0Likes
Like

Posted 25 December 2012 - 06:56 PM

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, 25 December 2012 - 06:56 PM.


#40 iMalc   Crossbones+   -  Reputation: 2306

Like
1Likes
Like

Posted 25 December 2012 - 08:21 PM

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
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS