Style guidance with checking bools

A

Angus

Hi

Is there anything to be gained by using:

if(!mybool)

as opposed to:

if(mybool == false)

Does the first variant use less cpu cycles or is it more efficient?
 
A

Alf P. Steinbach

* Angus:
Is there anything to be gained by using:

if(!mybool)

as opposed to:

if(mybool == false)
Yes.


Does the first variant use less cpu cycles or is it more efficient?

No, but it's a newbie misconception that that kind of efficiency matters.

First of all it doesn't matter when compared to correctness, clarity and so
forth, and second it doesn't matter compared to algorithmic efficiency.

The second variant marks the author as clueless.

And that's not only because of the verbosity but also because in practical
programming one very often has to deal with "boolean" types (such as the Windows
API BOOL type) where the possible values are not restricted to 'false' and
'true', and whence the habit of comparing to 'false' or 'true', and the like,
can easily introduce bugs.

For example, if 'b' is of Windows API type 'BOOL', then '!b' is a logical
negation, but 'b != true' is only a negation for the case where 'b' is 0.


Cheers & hth.,

- Alf
 
A

Alf P. Steinbach

* Victor Bazarov:
I would really question that given the name of that variable.

What would you expect the name of the variable in such an example to be?

Hello.

You're silly.

If the
variable is supposed to be 'true' or 'false', then the name is needed to
reflect that the meaning is. "mybool" is pointless. There is no
difference between !a or a != false, since 'a' is not readable.

I think you mean, "there is no difference with respect to readability".

That's a matter of (your) opinion, I'd guess most people disagree with you about
that, and there are certainly other differences.

Including the important one of not acquiring bad habits that can have really
undesired consequences in other contexts, and the one about expressing code in a
way that others are familiar with and can easily read.

Of
course if you have

if (!valid)

versus

if (valid == false)

then I second Alf's "yes".

It's not helpful to put that much importance on a name in an example.

And even with a name like 'x', use '!x' and not 'x == false'.

I hope that's the actual reason why one should prefer the logical not
over equality to false - don't create another chance for your
cluelessness to shine through.

What the **** do you mean?


What you snipped:

And that's not only because of the verbosity but also because in practical
programming one very often has to deal with "boolean" types (such as the Windows
API BOOL type) where the possible values are not restricted to 'false' and
'true', and whence the habit of comparing to 'false' or 'true', and the like,
can easily introduce bugs.

For example, if 'b' is of Windows API type 'BOOL', then '!b' is a logical
negation, but 'b != true' is only a negation for the case where 'b' is 0.


Cheers & hth.,

- Alf
 
V

Victor Bazarov

Alf said:
* Victor Bazarov:

What would you expect the name of the variable in such an example to be?

Hello.

You're silly.

No, I am not. And you sound (look) tired or drunk.
I think you mean, "there is no difference with respect to readability".

There is no difference if 'mybool' or 'a' is declared 'bool'.
That's a matter of (your) opinion, I'd guess most people disagree with
you about that, and there are certainly other differences.

Opinions are like ass holes. There are as many of them as there are
people. And, yes, of course it is a matter of my opinion! Answers
about style are nothing but.
Including the important one of not acquiring bad habits that can have
really undesired consequences in other contexts, and the one about
expressing code in a way that others are familiar with and can easily read.

That's a derivative.
It's not helpful to put that much importance on a name in an example.

Oh, I see. It's helpful to insist on the importance of the coding
practice on forming of habits potentially having ill effects on some
other contexts... OK.
And even with a name like 'x', use '!x' and not 'x == false'.



What the **** do you mean?

First off, please don't use that language with me.

Second, you should go to bed instead of guessing what others mean. If
you're tired, go rest. If you're drunk, go sober up. Russians say,
"Morning is wiser than night".

Naming of variables is *very important* unless the code is write-only
(not used to be read by anything except the compiler). But that's not
the point here.

The point is that if one doesn't want one's cluelessness to show, one
should prefer the logical not over the equality comparison with 'false'.
That's my statement rephrased. Read it over if you need. I can wait.

V
 
C

Chris M. Thomasson

Victor Bazarov said:
No, I am not. And you sound (look) tired or drunk.
[...]

Alf looks/sounds drunk? I cannot see him, nor can I hear him speaking right
now. Perhaps if I listen real hard I can hear his voice in through the
speakers...


Sorry about that, I could not resist...

;^)




BTW, if I can get my hands on a substance that can make other readers hear
my voice, see my image, well, I might be able to make some $$$ off that...
Any ideas?

:^o
 
C

Chris M. Thomasson

Chris M. Thomasson said:
Victor Bazarov said:
No, I am not. And you sound (look) tired or drunk.
[...]

Alf looks/sounds drunk? I cannot see him, nor can I hear him speaking
right now. Perhaps if I listen real hard I can hear his voice in through
the speakers...


Sorry about that, I could not resist...

;^)




BTW, if I can get my hands on a substance that can make other readers hear
my voice, see my image, well, I might be able to make some $$$ off that...
Any ideas?

Perhaps I should substitute the word `substance' which `chemical'?
 
N

Nick Keighley

even worse is

if (mybool == true)

I'd probably not allow code through a walk thru with a coding mistake
like that
I would really question that given the name of that variable.  If the
variable is supposed to be 'true' or 'false', then the name is needed to
reflect that the meaning is.

that's what declarations are for. A few lines before you'll find

bool mybool;
 "mybool" is pointless.  There is no
difference between !a or a != false,

yes there is.

<snip>

I tend to stick an "is" is boolean variable names

if (is_valid)

if (basestation_is_on_fire)
 
J

James Kanze

* Victor Bazarov:

[...]
I think you mean, "there is no difference with respect to
readability".
That's a matter of (your) opinion, I'd guess most people
disagree with you about that, and there are certainly other
differences.

If I understand correctly what he's saying, I agree with him.
Typically, my boolean variables don't have the word "bool" in
them. (They do almost always start with "is" or "are", or
sometimes "has".) I think what he's trying to say is that the
name should reflect the meaning, and in the case of boolean
variables, the meaning includes the sense: "isActive" will be
true when whatever it concerns is active, and "isNotActive" will
be true when whatever it concerns is not active. The important
thing is that the name tells you what true and false signify.

(Note that this also means that it isn't good design to define a
function, "doSomething" which returns true of false to indicate
success or failure, since which indicates success isn't clear.
In such cases, it's better to have an enum, with values
succeeded and failed, and test them explicitly, i.e.:

if ( doSomething() ) ... // bad
if ( doSomething() == true ) ... // worse
if ( doSomething() == succeeded ) ... // good

.. Of course, if the name of the function somehow indicates
whether true or false is success, then there's no problem with
the first, above. And some idioms, like the implicit conversion
of istream or ostream, are so ubiquious that we can easily live
with them.)
Including the important one of not acquiring bad habits that
can have really undesired consequences in other contexts, and
the one about expressing code in a way that others are
familiar with and can easily read.
It's not helpful to put that much importance on a name in an
example.

Yes and no. The name is the thing. It's not helpful that he
chose a bad name, although the "is" is perhaps implicit.
Something like "if ( validity )" tells me nothing. With "if (
valid )", I can probably guess. And with "if ( isValid )", it's
100% clear.
And even with a name like 'x', use '!x' and not 'x == false'.

Agreed. Except that you shouldn't have a boolean named 'x'.
 
J

James Kanze

Is there anything to be gained by using:

as opposed to:
if(mybool == false)
Does the first variant use less cpu cycles or is it more
efficient?

Who cares? The difference is probably not measurable, and
depends on the compiler.

The only real point here is readability, and what the code says
to the reader. The second form says that the author doesn't
understand basic logic or the C++ type system. An if requires
something that is logically a boolean. The purpose of using ==
in an if is to define a boolean condition concerning the two
operands involved. If one of the operands is already boolean,
it doesn't make sense. If you insist that a bool must be
compared to true or false in an if, then you'll never finish,
since the result of the comparison is also a bool. (In other
words, given "if ( mybool == false )", you'd have to in fact
write "if ( (mybool == false) == true )". And given that, you'd
have to write "if ( ((mybool == false) == true) == true )". And
so on, ad infinitum.)
 
A

Alf P. Steinbach

* James Kanze:
(Note that this also means that it isn't good design to define a
function, "doSomething" which returns true of false to indicate
success or failure, since which indicates success isn't clear.

C:\> help foo && echo "there's help on foo" || echo "no help on foo"
This command is not supported by the help utility. Try "x /?".
"there's help on foo"

C:\> help ver && echo "there's help on ver" || echo "no help on ver"
Displays the Windows XP version.

VER
"no help on ver"

C:\> _


- Alf
 
J

James Kanze

On 25 June, 01:02, Victor Bazarov <[email protected]> wrote:

[...]
that's what declarations are for. A few lines before you'll find
bool mybool;

That's not the point. The name "mybool" already says it's a
bool. It doesn't tell me anything about the actual meaning,
however. (In this case, it's probably chosen just for example's
sake, and doesn't necessarily reflect the naming conventions in
the actual program.) Typical names don't contain the word
"bool", and whether they do or don't isn't really the point: the
name should be indicative in some way that we are dealing with a
predicate, AND the directionality: "isActive" or "isNotActive",
for example.
I tend to stick an "is" is boolean variable names
if (is_valid)
if (basestation_is_on_fire)

Me too. Or an "are" if the thing is plurial. Or in some cases,
a "has": for a token in a parser, for example, "hasValue()".
(Some tokens, like an integral literal, have a value; others,
like an operator, don't.)
 
P

Pascal J. Bourguignon

James Kanze said:
* Victor Bazarov:
Alf P. Steinbach wrote:
* Angus:
[...]
If the
variable is supposed to be 'true' or 'false', then the name
is needed to reflect that the meaning is. "mybool" is
pointless. There is no difference between !a or a != false,
since 'a' is not readable.
I think you mean, "there is no difference with respect to
readability".

There is a difference with respect to readability.
You don't say "If it is hot is true then I'll go buy an ice-scream."
you say "If it is hot then I'll go buy an ice-scream."

So you should write:

if(it->isHot()){
goBuy(iceScream);
}

(Note that this also means that it isn't good design to define a
function, "doSomething" which returns true of false to indicate
success or failure, since which indicates success isn't clear.
In such cases, it's better to have an enum, with values
succeeded and failed, and test them explicitly, i.e.:

if ( doSomething() ) ... // bad
if ( doSomething() == true ) ... // worse
if ( doSomething() == succeeded ) ... // good

Even better design, reserve results for functions returning results:

try{
doSomething();
}catch(...){
// oops
}

and:

try{
result=computeSomething();
}catch(...){
// oops
}

Yes and no. The name is the thing. It's not helpful that he
chose a bad name, although the "is" is perhaps implicit.
Something like "if ( validity )" tells me nothing. With "if (
valid )", I can probably guess. And with "if ( isValid )", it's
100% clear.


Agreed. Except that you shouldn't have a boolean named 'x'.

And notice that <iso646.h> for C and <ciso646) for C++ are standard
headers, so you can write the even more readable:

if(not isHot and isRaining){
stayAt(Home);
}
 
K

Krice

The only real point here is readability, and what the code says
to the reader.

I think mybool==false is more readable and consistent.
Also, I believe it's valid C++ language and works like
it says.
About variable naming, I think it's dumb to name them
like is_banana or mybool. There is no need for notation,
because the variable has a type already.
 
J

Juha Nieminen

Krice said:
I think mybool==false is more readable and consistent.

if((((mybool == false) == false) == false) == false)

How long before you figure out what that is equivalent to?
 
K

Krice

    if((((mybool == false) == false) == false) == false)

  How long before you figure out what that is equivalent to?

Excuse me, but what is that apeshit code example?
 
J

Juha Nieminen

Krice said:
Excuse me, but what is that apeshit code example?

Just following your suggestion that comparing booleans to 'false'
makes the code more readable.
 
J

James Kanze

James Kanze said:
* Victor Bazarov:
Alf P. Steinbach wrote:
* Angus:
[...]
If the variable is supposed to be 'true' or 'false', then
the name is needed to reflect that the meaning is.
"mybool" is pointless. There is no difference between !a
or a != false, since 'a' is not readable.
I think you mean, "there is no difference with respect to
readability".
There is a difference with respect to readability.
You don't say "If it is hot is true then I'll go buy an ice-scream."
you say "If it is hot then I'll go buy an ice-scream."
So you should write:
if(it->isHot()){
goBuy(iceScream);
}

Excellent example. (Wish I'd thought of it.)
Even better design, reserve results for functions returning results:
try{
doSomething();
}catch(...){
// oops
}

try{
result=computeSomething();
}catch(...){
// oops
}

That depends on a lot of things. If it's in the functions
nature to "fail" ("failure" is a normal result), then using
exceptions is obfuscation, and should be avoided. If the
function normally returns a value, but failure is an expected
occurance, then returning some sort of fallible is in order
(either a Fallible class, or a pointer, which can be NULL). If
the function doesn't return any other value, then it makes
perfect sense for it to return a success code, so that the
client code can handle it immediately, rather than defering
treatment to the end of the block.
And notice that <iso646.h> for C and <ciso646) for C++ are standard
headers, so you can write the even more readable:
if(not isHot and isRaining){
stayAt(Home);
}

Yes. In this context, "readable" is a very personal attribute.
People like me, who've been programming C and C++ for over
twenty years, probably find "if ( ! isHot && isRaining )" more
readable (but in another language, I'd willingly write:
IF NOT isHot AND isRaining THEN ...).

At least one C++ expert (Francis Glassborow) does recommend
using the symbolic names. Logically, it certainly seems like a
good idea. Provided everyone, or at least a large majority of
the authors, do it. But doesn't look like that's happening.
 
J

James Kanze

The problem I have with functions returning enums for
failure/success is that it tend to become very easily subject
to inflation:
Starts with the concept presented above with:
enum { succeeded, failed } FunctionReturn;
Superficially fine.. but then someone comes in and decide to apply
inflation:
enum { succeeded, failure_minor, failure_major } FucntionReturn;

At least one software provider has done this with BOOL:).

Obviously, the concept can be misused. And just as obviously,
sometimes it's a good idea to provide more information
concerning the cause of failure: I have a number of functions
which return something like:

enum Results { ok, errorCause1, errorCause2, ... } ;

This is especially relevant when parsing---you want to be able
to tell the user what was wrong with his input. (Note that this
is very close to the Posix conventions for new functions: return
an int, with 0 for success, and an error code for failure.)
 
J

Juha Nieminen

Bill said:
Best not to feed the trolls.

Hey, that's a great counter when someone questions your claim. Rather
than explaining why the counter-argument makes no sense, simply dismiss
it as "trolling". That way you can keep your opinion and still come out
as the "winner" of the discussion. Excellent tactic.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,417
Latest member
DarrenGaun

Latest Threads

Top