Skip to content

Booleans

Artemis edited this page May 12, 2023 · 2 revisions

Booleans in C++

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.

Declaring Booleans

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

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

Boolean Values

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

Converting to Booleans

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

Conclusion

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.

Clone this wiki locally