-
-
Notifications
You must be signed in to change notification settings - Fork 1
Booleans
Booleans are a fundamental data type used in programming, and C++ is no exception. A boolean value is a value that represents either true or false, and they are often used in control flow to tell the program which path to execute in a given situation. In C++, booleans are implemented using the bool
keyword.
To declare a boolean variable, you simply use the bool
keyword followed by the variable name that you want to use. For example:
bool isHappy = true;
Boolean operators are used to compare two boolean values and return a new boolean value based on the comparison. The following operators are available in C++:
-
&&
(and) - Returns true if both values are true -
||
(or) - Returns true if either value is true -
!
(not) - Returns the opposite of the given value
For example:
bool isHappy = true;
bool isSad = false;
bool isMixed = isHappy && isSad; // isMixed = false
bool isOne = isHappy || isSad; // isOne = true
bool notHappy = !isHappy; // notHappy = false
Booleans can only have one of two values: true
or false
. These values can be assigned directly, or they can be the result of a comparison. For example:
bool isHappy = true;
int age = 18;
bool isAdult = age >= 18; // isAdult = true
Booleans can also be converted from other data types. Any non-zero value will be converted to true
, and zero will be converted to false
. For example:
int x = 5;
bool isPositive = (bool)x; // isPositive = true
Booleans are an important data type in programming and C++ provides support for them through the bool
keyword. They can be declared, compared, and converted from other data types, and they provide a powerful way to control program flow.