C++ Boolean Type

Introduction

Let us declare a variable b of type bool.

This type holds values of true and false.

int main() 
{ 
    bool b; 
} 

This example declares a variable b of type bool.

The variable is not initialized, no value has been assigned to it at the time of construction.

To initialize a variable, we use an assignment operator = followed by an initializer:

int main() 
{ 
    bool b = true; 
} 

We can also use braces {} for initialization:

int main() /*from  ww  w .  ja v  a 2  s . co  m*/
{ 
    bool b{ true }; 
} 

These examples declare a (local) variable b of type bool and initialize it to a value of true.

Our variable now holds a value of true.

All local variables should be initialized.

Accessing uninitialized variables results in Undefined Behavior.




PreviousNext

Related