Boolean values in C++ tell us whether a given expresson is true, i.e. 1, or false, i.e. 0.
A Boolean variable is one that is declared with the bool keyword. This type of variable can only take either true or false as its value.
#include <iostream>using namespace std;int main() {// creating bool variablesbool iLoveCoding = true;bool iLoveCrayfish = false;// returning a boolean valuecout << iLoveCoding << "\n";cout << iLoveCrayfish;return 0;}
Here is a line-by-line explanation of the code above:
Lines 6-7: We create Boolean variables, iLoveCoding and iLoveCrayfish, and assign a Boolean value to each of them.
Lines 10-11: We return and print our variables.
It is worth noting that a
truevalue will return1and afalsevalue will return0.
A Boolean expression in C++ is that type of expression that will return a Boolean value: either 1 (true) or 0 (false).
When we write a Boolean expression to compare two values in C++ using the comparison operator, the return value is a Boolean.
#include <iostream>using namespace std;int main() {// greater than operatorcout <<"(1 > 2) = " << (1 > 2)<< "\n";// less than operatorcout <<"(1 < 2) = " << (1 < 2)<< "\n";// equal to operatorcout <<"(1 == 2) = " << (1 == 2)<< "\n";// not equal to operatorcout <<"(1 != 2) = " << (1 != 2)<< "\n";// greater than or equal to operatorcout <<"(1 >= 2) = " << (1 >= 2)<< "\n";// less than or equal to operatorcout <<"(1 <= 2) = " << (1 <= 2);return 0;}
From the output of the code above, we can see that the expressions which are true (e.g., (1<2)) return 1, while the expressions which are false ( e.g., (1>2)) return 0.