Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

C++ Booleans

Booleans

In C++, boolean data type is represented by the bool keyword. A boolean variable can hold one of two values: true or false. This data type is commonly used for representing logical values and for making decisions within programs.

In programming, you will need a data type that can only have one of two values, like:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false:

Example:

#include <iostream>
using namespace std;

int main() {
  bool isCodingFun = true;
  bool isFishTasty = false;
  cout << isCodingFun << "\n";
  cout << isFishTasty;
  return 0;
}

Output:

​1
0

From the example above, you can read that a true value returns 1, and false returns 0.

Boolean Expressions

Boolean expression returns a boolean value that is either 1 (true) or 0 (false).

This is useful to build logic, and find answers.

You can use a comparison operator, such as the greater than (>) operator, to find out if an expression (or variable) is true or false:

Example:

#include <iostream>
using namespace std;

int main() {
  int x = 10;
  int y = 9;
  cout << (x > y);
  return 0;
}

Output:

1

Or even easier:

Example:

#include <iostream>
using namespace std;

int main() {
  cout << (10 > 9);
  return 0;
}

Output:

1

In the examples below, we use the equal to (==) operator to evaluate an expression:

Example:

#include <iostream>
using namespace std;

int main() {
  int x = 10;
  cout << (x == 10);
  return 0;
}

Output:

1

Example:

Output “Old enough to vote!” if myAge is greater than or equal to 18. Otherwise output “Not old enough to vote.”:

#include <iostream>
using namespace std;

int main() {
  int myAge = 35;
  int votingAge = 18;

  if (myAge >= votingAge) {
    cout << "Old enough to vote!";
  } else {
    cout << "Not old enough to vote.";
  }
  return 0;
}

Output:

Old enough to vote!

    Leave a Reply

    Your email address will not be published.

    Need Help?