• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
xiajia

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

 

 

?

 

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
0

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0