How to use bool variable.

Started by
46 comments, last by Trienco 11 years, 4 months ago

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

I don't treat any of these as rules, but there's plenty of benefit to maximizing readability.

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

?


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.

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

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.

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

[size=2][ 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 ]

if(a = true)

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

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.

[size=2][ 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 ]

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.

This topic is closed to new replies.

Advertisement