Noob question...

I need an explantion of how, bool works, or when to use it...
A bool holds either true of false. It is good for when you need a variable that can only be one of those two states, such as whether a switch is on or off.
OK thanks
You generally use it to make something easier to understand, or for a slight performance increase, when working on a 1 byte bool holding values, 1/0 true/false. (Rather than an int)

true/false can be used with booleans, etc:
1
2
3
4
5
6
7
8
9
10
Toilet toilet;
toilet.vacant = true;

if (toilet.vacant == false) {}
//Or
if (!toilet.vacant) {}

if (toilet.vacant == true) {}
//Or
if (toilet.vacant) {}


Easier to read than 1, 0.
Last edited on
Line 6

if (!toilet.vacant) {}

What is the "!" for?
Negation of truth values.

!true = false
!false = true

Means the opposite value when dealing with bool in C++.

That line in English could be said, if toilet.vacant is false, then this condition is true.
Last edited on
Another example please
its a operator that equals the oppisite of the true or false value so,

bool a = true;

cout<<!a; // this would output false or 0 (0 means false, any thing else then 0 is true)


now, you don't have to use a bool but a bool is more efficent for some things...

int a =0;
int b=69; // or what ever other non-0 number
bool c= false;
bool d=true;

if (a)/*will not excute*/;
if (b)/*will excute*/;
if (c)/*will not excute*/;
if (d)/*will excute*/;
if (!c)/*will excute*/;
if (!d)/*will not excute*/;
Topic archived. No new replies allowed.