Boolean Data Type In C++ With Example

Boolean Data Type ?

The "boolean" data type is used to represent boolean values that returns either "true" or "false". Where in, value '1' returns true and value '0' returns false.


Boolean data type :

Boolean variables are variables that can have only two possible values: true, and false.

To declare a Boolean variable, we use the keyword bool.

         bool b;

To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.

         bool b1 { true };
       bool b2 { false };
       b1 = false;

Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becoms the integer 1, and false becoms the integer 0.


Example 1:



Output :

    
      1
      0
      0
      1


Example 2:

#include <stdio.h>
#include <stdbool.h>
 
int main(void)
{
    bool a=true, b=false;
    printf("%d\n", a&&b);
    printf("%d\n", a||b);
    printf("%d\n", !b);
}

Output :

   
    0
    1
    1

Example 3:

// CPP program to illustrate bool  
// data type in C++ 
#include<iostream> 
using namespace std; 
int main() 
{ 
    int x1 = 10, x2 = 20, m = 2; 
    bool b1, b2; 
    b1 = x1 == x2; // false 
      
    b2 = x1 < x2; // true 
      
    cout << "b1 is = " << b1 << "\n"; 
    cout << "b2 is = " << b2 << "\n"; 
    bool b3 = true; 
      
    if (b3) 
        cout << "Yes" << "\n"; 
    else
        cout << "No" << "\n"; 
          
    int x3 = false + 5 * m - b3; 
    cout << x3; 
      
return 0; 
      
} 

Output :

    b1 is = 0
    b2 is = 1
    Yes
    9