Followers 0

# How to use bool variable.

## 47 posts in this topic

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?

Edited by xiajia
2

##### Share on other sites
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.
0

##### Share on other sites

They compile exactly the same.

0

##### Share on other sites
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. ;)
0

##### Share on other sites

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

1

##### Share on other sites
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?

Edited by xiajia
0

##### Share on other sites

[quote]

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

[quote]

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.

[quote]

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.

1

##### Share on other sites

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!

Edited by MarkS
0

##### Share on other sites

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

Observe:

[code]int myInteger = 0; if(myInteger == 0)[/code]

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

[code]bool operator==(int, int)[/code]

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:

[code]bool theTwoAreEqual = (myInteger == 0);[/code]

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

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

You don't need to say:

[code]if((myInteger == 0) == true)[/code]

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

[code]if(myBool == true)[/code]

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

[code]bool result = (boolOne && boolTwo) || !boolThree;[/code]

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.

1

##### Share on other sites
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. Edited by Stroppy Katamari
0

##### Share on other sites

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()) {
...
1

##### Share on other sites
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.

Edited by MarkS
0

Edited by MarkS
0

##### Share on other sites
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.

0

##### Share on other sites

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

[code]bool foo() {
bool a = false;
if (a = true)
return true;
return false;
}
[/code]

[quote]> 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]

2

##### Share on other sites

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

0

##### Share on other sites
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.
1

##### Share on other sites
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.
0

##### Share on other sites

A comparison is more explicit than an expression which implicitly converts to bool.  In my opinion this enhances readability.
[table][tr][td] [/td][td]

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

[/td][/tr][/table]
Also, when possible, I prefer testing for equality to testing for inequality.
[table][tr][td] [/td][td]

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

[/td][/tr][/table]
Along the same lines, I prefer to pass enumerated values as parameters over integers or Boolean values.
[table][tr][td] [/td][td]

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

[/td][/tr][/table]
There's plenty of benefit to maximizing readability.

0

##### Share on other sites
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++.

0

##### Share on other sites

?

bool a;
bool b;
bool fa();
bool fb();
{
//do true
}
{
//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
0

##### Share on other sites

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
0

## Create an account

Register a new account