1. boolean

Boolean data type is used to represent or hold the truth values, either true or false. If you want to declare a data of type boolean, use the keyword bool follow by the of the data. For example :

int main(){

    bool myVariable; // declare a data with the name myVariable with the type bool.

    return 0;
}


Variable of type bool will take 1 byte ( or 8 bits) in memory.

After declaration of a boolean type the address of this data in memory will have a value of zero by default, which means false. And true will have a value of 1.

We can print the value of this value :

int main(){

    bool myVariable; 
    std::cout << myVariable << std::endl; // print the default value which is zero.

    return 0;
}


To initialize means put a value at the memory address. We can do this by using the equal operator, for example :

int main(){

    bool myVariable; 
    std::cout << myVariable << std::endl; // print the default value which is 0.


    myVariable = true;
    std::cout << myVariable << std::endl; // print the initialize value which is 1.

    return 0;
}


We can print textual form of boolean data (true and false) using boolean flag format std:boolalpha define in iostream header file.

How it works is :

  • - if this flag is present you print bool type that has a value true , it print true and false print false
  • - if this flag is not present, true will print 1 and false will print 0

Example :

#include <iostream>



int main() {

    bool varFalse = false;
    bool varTrue = true;

    std::cout << "before defining std::boolalpha" << std::endl;
    std::cout << varFalse << std::endl;
    std::cout << varTrue << std::endl;

    std::cout << std::boolalpha << std::endl; // define the boolean format flag

    std::cout << "after defining std::boolalpha" << std::endl;
    std::cout << varFalse << std::endl;
    std::cout << varTrue << std::endl;

    return 0;
}