Boolean (bool) is a data type that can store only two values: true or false. It is used to represent logical conditions or binary states in a program.
- Internally, true is represented as 1 and false as 0, so boolean values can be used in arithmetic expressions.
- Integer or floating-point values can be implicitly converted to bool (0 becomes false and any non-zero value becomes true).
C++
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
// Boolean variables
bool isEqual = (a == b);
bool isSmaller = (a < b);
cout << "Is a equal to b? " << isEqual << endl;
cout << "Is a smaller than b? " << isSmaller << endl;
// Using bool in if statement
if (isSmaller)
cout << "a is smaller than b" << endl;
else
cout << "a is not smaller than b" << endl;
return 0;
}
OutputIs a equal to b? 0
Is a smaller than b? 1
a is smaller than b
Important Points
1. The default numeric value of true is 1 and false is 0.
2. We can use bool-type variables or values true and false in mathematical expressions also. For instance,
int x = false + true + 6;
It is valid and the expression on the right will evaluate to 7 as false has a value of 0 and true will have a value of 1.
3. It is also possible to convert implicitly the data type integers or floating point values to bool type.
Example:
bool x = 0; // false
bool y = 100; // true
bool z = 15.75; // true
5. The most common use of the bool datatype is for conditional statements. We can compare conditions with a boolean, and also return them telling if they are true or false.
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems