advantage of bool?

I just started learning c++ and i came across the built in data types and i am not able to understand what exactly is the advantage of having a bool data type, some one please help me
Last edited on
bool is a very important data type that has only two possible states, true (or non-zero) or false (or 0).

It is widely used in conditional 'if' statements and for, while loops.

if ( some Boolean expression is true) { 
//   do something. This executes if the above Boolean expression evaluates to true.

while ( ! (some Boolean variable) ) {

   // Keep doing this. These statements are repeatedly executed until the above Boolean
  // variable becomes false.

Moreover, there can be functions that return bool datatype, to be used in further conditional statements.

EDIT: bool true corrected.
Last edited on
Historically C and C++ allow use of int for conditional expressions. I suppose that is why the question is asked.

Using bool instead of int will not change program significantly, however it is considered improving readability, maintainability etc.
closed account (S6k9GNh0)
It might also be an optimization as far as memory size and operations concerning booleans.

I would look into masks as well.
Just a minor correction. false is 0 and true is not-zero. When you cast a bool to an int, this is converted to 1. However this statement is also true:
int i = 2;
if (i == true) 

@Stewbond, Thanks for pointing out.

Ok so bool converts all non zero integers to true and zero to false right?
so is this valid?
bool b=-4;
if (bool)
You mean if ( b ).

Yes the cout statement shall execute.
all the numeric data types can be transformed to bool implicitly, following the rule 0 == false, others == true, which cause the trouble of
int a = 20;
int b = 30;
if(a = b) {}
if(a == b) {}

i do not think this is an advantage in c++, but it's the legacy problem. and usually someone will tell you to write like,
if(20 == a) {}

to avoid such trouble.

but pay attention to vector<bool>, it's a specialization of vector template, which uses 1 bit, 1 == true, 0 == false. this can help to save memory, but the trouble is,
vector<bool> vb;
for(int i = 0; i < 100; i++) vb.push_back(true);
bool& t = vb[0];

which is wrong.
Sorry Abhishek tat was my mistake , i jus started learning yesterday so little confusion and thanks to everyone ,now i am clear about using the data type bool, and can someone give me an easy example to explain polymorphism?
@Stewbond: please cut your left hand

> However this statement is also true:
┬┐which statement?
Topic archived. No new replies allowed.