4.13. Boolean VariablesΒΆ

As usual, for every type of value, there is a corresponding type of variable. In C++ the boolean type is called bool. Boolean variables work just like the other types:

bool fred;
fred = true;
bool test_result = false;

The first line is a simple variable declaration; the second line is an assignment, and the third line is a combination of a declaration and as assignment, called an initialization.

As I mentioned, the result of a comparison operator is a boolean, so you can store it in a bool variable

bool even = (n % 2 == 0);     // true if n is even
bool plus = (x > 0);          // true if x is positive

and then use it as part of a conditional statement later:

if (even) {
  cout << "n was even when I checked it";
}

A variable used in this way is called a flag, since it flags the presence or absence of some condition.

Q1

Match the conditional statement to the correct boolean, given x = 2.

Q2

Match the statement to the word that describes it best.

Q3

What will print?

int n = 16;
int x = 4;

bool even_flag = (n % 2 == 0);
bool plus_flag = (x > 0);

if (even_flag) {
  cout << "n was even when I checked it ";
}

if (plus_flag) {
  cout << "x was positive when I checked it";
}

Q4

What will print?

bool low_battery=true;
bool power_outage=true;

if(low_battery){

  if(power_outage){
      power_outage=!power_outage;
  }
  else{
      low_battery=false;
  }

  if(!power_outage){

    if(low_battery){
        cout<<"Charging your phone"<<'\n';
    }
    else{
        cout<<"Battery is charged"<<'\n';
    }

  }
  else{
    cout<<"There is no power"<<'\n'>>;
  }
}


More to Explore