C++ Tutorial C++ Advanced C++ Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ - Booleans



There are many instances in the programming, where a user need a data type which represents True and False values. For this, C++ has a bool data type, which takes either True or False values.

Boolean Values

A boolean variable is declared with bool keyword and can only take boolean values: True or False values. In the example below, a boolean variable called MyBoolVal is declared to accept only boolean values.

#include <iostream>
using namespace std;

int main (){
  bool MyBoolVal = true;
  cout<<MyBoolVal<<"\n"; //returns 1 (true)

  MyBoolVal = false;
  cout<<MyBoolVal<<"\n"; //returns 0 (false)
  return 0;
}

The output of the above code will be:

1
0

Boolean Expressions

A boolean expression in C++ is an expression which returns boolean values: 1 (true) or 0 (false) values. In the example below, comparison operator is used in the boolean expression which returns 1 when left operand is greater than right operand else returns 0.

#include <iostream>
using namespace std;

int main (){
  int x = 10;
  int y = 25;

  cout<<(x > y)<<"\n"; //returns 0 (false)
  return 0;
}

The output of the above code will be:

0

A logical operator can be used to combine two or more conditions to make complex boolean expression like && operator is used to combine conditions which returns 1 (true) if all conditions are true else returns 0 (false). Please see the example below.

#include <iostream>
using namespace std;

int main (){
  int x = 10;

  cout<<(x > 0 && x < 25)<<"\n"; //returns 1 (true)
  return 0;
}

The output of the above code will be:

1

5