Operators Boolean CPP
Operators Boolean CPP
Operators
Equal To
C++ uses the == operator to determine equality. Beginners often confuse the
= and the == operators. Remember, = is the assignment operator.
int a = 5;
int b = 5;
cout << boolalpha << (a == b) << endl;
challenge
Not Equal To
The != operator checks to see if two values are not equal.
int a = 5;
int b = 5;
cout << boolalpha << (a != b) << endl;
challenge
Less Than
The < operator is used to check if one value is less than another value.
int a = 5;
int b = 7;
cout << boolalpha << (a < b) << endl;
challenge
Hint(s)
It is possible to declare and assign int b = false; because false is just a
value of 0. Since 5 is not less than 0, false is returned.
int a = 5;
int b = 7;
cout << boolalpha << (a <= b) << endl;
challenge
Hint(s)
false is less than true because 0 is less than 1.
Greater Than & Greater Than or
Equal To
Greater Than
The > operator is used to check if one value is greater than another value.
int a = 9;
int b = 17;
cout << boolalpha << (a > b) << endl;
challenge
Hint(s)
9 is both greater than the value of false, which is 0, and the value of true,
which is 1.
int a = 9;
int b = 17;
cout << boolalpha << (a >= b) << endl;
challenge
Hint(s)
true is greater than false.
And
bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a && b) << endl;
challenge
bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a && b && c) << endl;
challenge
Hint(s)
c is the only variable is that is false. Thus, if c is involved in an &&
expression, the entire thing will evaluate to false. Any combinations of as
and/or bs will result in true.
Or
The || Operator
The || (or) operator allows for compound (more than one) boolean
expressions. If at least one boolean expression is true, then the whole thing
is true. To be false, all boolean expressions must be false.
bool a = true;
bool b = true;
bool c = false;
bool d = false;
cout << boolalpha << (a || b) << endl;
challenge
Multiple || Statements
You can chain several || expressions together. They are evaluated in a left-to-
right manner.
bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a || b || c) << endl;
challenge
Replace (a || b || c) in the code above with (c && c && c && c && c)?
Not
The ! Operator
The ! (not) operator produces the opposite result of the boolean expression
that it modifies.
challenge
Hint(s)
The ! operator works similarly to how a - (negative) sign works in
mathematics. The - of a positive number is a negative number and the - of
a negative number is a positive number.
1. Parentheses ()
2. Not !
3. And &&
4. Or ||
Short Circuiting
Short Circuiting
If C++ can determine the result of a boolean expression before evaluating
the entire thing, it will stop and return the value.
.guides/img/ShortCircuiting