Skip to main content
GameDev.net gamedev.net
🔒 Locked

How to use bool variable.

Started by xiajia Dec 24, 2012 at 6:19 AM 46 replies 9.6k views
Original Post
xiajia
xiajia

When I use a variable of type bool.People warned me:you'd better written if(a == true) as if(a). I do not know why we must do this. What are the advantages of doing?

My opinion, simply follow the following principles: 'bool' defined variables must be used and can only use 'true' and 'false' initialization and assignment, in the judgment must be written as if (a == true) or if (a== false).
then can avoid all ambiguity and hidden meaning.

Is that true?

Sik_the_hedgehog
Sik_the_hedgehog

The reasoning behind that logic is this: if a is true, then a == true returns true. If a is false then a == true returns false. So... basically it's just redundant. Doesn't hurt if you explicitly make the comparison, though, so honestly don't bother much about it.

EDIT: also if somebody ever tells you that the comparison makes the program slower, tell them the compiler is smart enough to optimize it. I hope you don't meet such a person, but that could happen.

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.
LennyLen
LennyLen
Your opinion is quite correct. Both if(a) and if(a == true) are equivalent, and while to an experience C/C++ coder there will be no ambiguity, having if(a == true) is clearer to people who are not so used to reading code.
iMalc
iMalc
If it seems clearer putting == true on the end, then you possibly aren't using good variable names.
People don't go around saying "if paused equals true then ...". They'd say "if paused then ..."

Besides, where do you stop the redundancy?:
if ((a == true) == true)
if (((a == true) == true) == true)

This is one of those times where I believe it's a case of "correct your thinking".
Khatharr
Khatharr

They compile exactly the same.

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.
LennyLen
LennyLen
People don't go around saying "if paused equals true then ...". They'd say "if paused then ..."
If you're going to compare to a natural language, you need to use the language correctly. Saying "If paused then..." is not correct English, as it lacks a subject. Used correctly you would say "If the recording is paused..." So the more verbose comparison (if(a == true)) is actually the form used in English.
This is one of those times where I believe it's a case of "correct your thinking".

Which could also be said in regard to your use of the English language. ;)
Khatharr
Khatharr

To clarify, the if statement simply checks for equality with zero. If the value provided is equal to zero then the test is considered 'false'. Otherwise it's considered 'true'. The bool values are typically defined "false = 0" and "true = !false". So if(x) can be thought of as "If x is non-zero then ...".

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

bool a;  //no initialized
if(a == true)
{
    //do 1
}
if(a == false)
{
   //do 2
}


Result is not 'do 1' nor 'do 2'.'a' is not initialized. 'a' is not 'true' nor 'false'.This is contrary to the definition of 'bool' logic.'bool' variable is either 'true' or 'false'.Can not have the other values.According to the interpretation of a friend before.'true' should be a logical value, rather than an actual value.That is 'true' should be '! false', rather than the other what the exact value.But that there is no way to express in a programming language.We can refer to a lot about bool definition.

in VS "windef.h"


typedef int BOOL;
#define FALSE 0
#define TRUE 1

in SDL


typedef enum 
{ 
    SDL_FALSE = 0, 
    SDL_TRUE  = 1
}SDL_bool;

People trying to use an exact value represents the 'true', But this logic is wrong.So I think that should be realized through the state variables to solve this problem.the method I mentioned before.
For example:


bool a = 2;
if(a)
{ 
//do true
}
if(!a)
{ 
//do false
}

the result is 'do true'.It is correct from logical?

rip-off
rip-off

If you're going to compare to a natural language, you need to use the language correctly. Saying "If paused then..." is not correct English, as it lacks a subject. Used correctly you would say "If the recording is paused..." So the more verbose comparison (if(a == true)) is actually the form used in English.

[/quote]

I don't follow this. The translation of "if(paused == true)" to english would be something like "If it is true that the recording is paused".

When I use a variable of type bool.People warned me:you'd better written if(a == true) as if(a). I do not know why we must do this.

[/quote]

I'd advise the opposite, don't compare with the literal value for boolean variables.

What are the advantages of doing?

[/quote]

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.

MarkS_
MarkS_

Besides, where do you stop the redundancy?:


if ((a == true) == true)

if (((a == true) == true) == true)

This is one of those times where I believe it's a case of "correct your thinking".

Really well put!

Servant of the Lord
Servant of the Lord

if() statements take a bool. Think of it like a function, taking a single bool parameter.

Observe:

int myInteger = 0; if(myInteger == 0)

The '==' symbol is actually a function with special syntax:

bool operator==(int, int)

It takes two parameters (one on the left of the == and one on the right), and returns a bool that is 'true' if they are both equal.

Try this code:

bool theTwoAreEqual = (myInteger == 0);

if() statements, being similar to (but not exactly) a function that takes a single parameter, and that parameter is always a single bool.

bool equation = (myInteger == 0); if(equation) { //...do stuff... }

You don't need to say:

if((myInteger == 0) == true)

bools are already true or false. if() statements already take a bool. The code:

if(myBool == true)

...is unnecessarily redundant, but a perfectly acceptable coding style.

The == function takes two values and returns a bool if they are equal.

The != function takes two values and returns a bool if they are not equal.

Likewise the < > <= >= functions return bools.

The ! operator also returns a bool.

The && and || operators also return bools:

bool result = (boolOne && boolTwo) || !boolThree;

If you have a bool already, you might as well just pass it to the if() statement, but there's no real harm in doing it the other way.

If statements say, "if(whatever in here is true)". Bools already know whether they are true or not without having to do comparison.

Stroppy Katamari
Stroppy Katamari
If there's one thing a beginner should be mindful of when writing conditional statements, it is to write comparisons with const value first. "if(true == a)" instead of "if(a == true)" because it prevents accidental assignment.

But when a is bool, "if(a)" is best anyway.
alvaro
alvaro

People don't go around saying "if paused equals true then ...". They'd say "if paused then ..."

If you're going to compare to a natural language, you need to use the language correctly. Saying "If paused then..." is not correct English, as it lacks a subject. Used correctly you would say "If the recording is paused..." So the more verbose comparison (if(a == true)) is actually the form used in English.



You can make things more readable by making it clear in the name of a method that it returns a boolean. You can then say:
  if (recording.is_paused()) {
      ...
MarkS_
MarkS_
If there's one thing a beginner should be mindful of when writing conditional statements, it is to write comparisons with const value first. "if(true == a)" instead of "if(a == true)" because it prevents accidental assignment.

But when a is bool, "if(a)" is best anyway.

Bull. That notation needs to die a horrible death! It is unnecessary and looks stupid. They mean the same thing, but one reads really weird. You truly gain nothing from that.

MarkS_
MarkS_

Oops. Quote instead of edit...

Cornstalks
Cornstalks
If there's one thing a beginner should be mindful of when writing conditional statements, it is to write comparisons with const value first. "if(true == a)" instead of "if(a == true)" because it prevents accidental assignment.

But when a is bool, "if(a)" is best anyway.

Bull. That notation needs to die a horrible death! It is unnecessary and looks stupid. They mean the same thing, but one reads really weird. You truly gain nothing from that.

I've seen bugs introduced because a programmer accidentally wrote if (someVar = SOME_VALUE) instead of if (someVar == SOME_VALUE). It's not very frequent, but this bug does exist in production code in various products. And beginners are more likely to make it themselves (I remember doing it myself). At the last place I worked at the coding standard was to do if (SOME_VALUE == someVar) simply to guard against the rare chance that there's a typo when writing the if statement.

I've found that, at least for me, I've gotten to the point where various rules and coding standards don't bother me anymore. I have my own personal style, but after having worked enough with other coding styles, it's no longer knives in my eyes when curly braces aren't on their own line, or the variable is on the right side when doing a comparison, or when members are prefixed with m_ (or some variant), etc.

alvaro
alvaro

[quote name='Cornstalks' timestamp='1356379505' post='5014011']
I've seen bugs introduced because a programmer accidentally wrote if (someVar = SOME_VALUE) instead of if (someVar == SOME_VALUE). It's not very frequent, but this bug does exist in production code in various products. And beginners are more likely to make it themselves (I remember doing it myself). At the last place I worked at the coding standard was to do if (SOME_VALUE == someVar) simply to guard against the rare chance that there's a typo when writing the if statement.
[/quote]

I think if you are disciplined enough to remember to put the constant first, you are also disciplined enough to use the correct operator. 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.

bool foo() {
bool a = false;
if (a = true)
return true;
return false;
}

> g++ test.cpp -c -Wall
test.cpp: In function ‘bool foo()’:
test.cpp:3:15: warning: suggest parentheses around assignment used as truth value[/quote]

superman3275
superman3275

I've seen bugs introduced because a programmer accidentally wrote if (someVar = SOME_VALUE) instead of if (someVar == SOME_VALUE). It's not very frequent, but this bug does exist in production code in various products. And beginners are more likely to make it themselves (I remember doing it myself). At the last place I worked at the coding standard was to do if (SOME_VALUE == someVar) simply to guard against the rare chance that there's a typo when writing the if statement.

I think if you are disciplined enough to remember to put the constant first, you are also disciplined enough to use the correct operator. 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.


bool foo() {
  bool a = false;
  if (a = true)
    return true;
  return false;
}

> g++ test.cpp -c -Wall
test.cpp: In function ‘bool foo()’:
test.cpp:3:15: warning: suggest parentheses around assignment used as truth value


Although I agree with CornStalks about style, Alvaro made a good point.

Specifically remembering to compare using


if(VALUE == VARIABLE)
{
//code
//code
}

is pointless, considering if you remember to specifically compare in this order you will in-turn remember to use ==.

I would say you should use if (a) mainly because if(a == true) is simply extra typing, and it will help later on if(object.member_variable) is better than if(object.member_variable == true) because when you have numbers that you must compare to true or false the Compiler will give you a warning when you say if(number == boolean). (Imagine loading a binary file and comparing the values given).

Cornstalks
Cornstalks
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.
LennyLen
LennyLen
I don't follow this. The translation of "if(paused == true)" to english would be something like "If it is true that the recording is paused".

I wasn't actually trying to translate it literally into English. I was simply pointing out that in English you need a subject to compare a state to.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.