In C++, a boolean is a data type that can have only two possible values: true or false. It is a fundamental data type that is used in conditional statements, loops, and other programming constructs. This article will explore the boolean data type in detail, including its syntax, operators, and examples.
Boolean Data Type Syntax The boolean data type is defined in C++ using the keyword bool. A variable of type bool can have only two values: true or false. Here is the syntax to define a boolean variable:
bool myBoolVariable;
The above syntax creates a boolean variable called myBoolVariable with an initial value of false. You can assign the value of true or false to this variable as follows:
myBoolVariable = true;
Boolean Operators C++ provides a set of boolean operators that allow you to perform logical operations on boolean values. Here are some of the most commonly used boolean operators:
Logical NOT (!):
This operator is used to negate a boolean value. For example:
bool myBoolVariable = true;
bool negatedVariable = !myBoolVariable; // negatedVariable is false
Logical AND (&&):
This operator returns true if both of its operands are true. For example:
bool a = true;
bool b = false;
bool c = a && b; // c is false
Logical OR (||):
This operator returns true if at least one of its operands is true. For example:
bool a = true;
bool b = false;
bool c = a || b; // c is true
Boolean Examples Let’s look at some examples of how booleans can be used in C++:
Example 1:
Checking if a number is even or odd using a boolean variable
int myNumber = 10;
bool isEven = (myNumber % 2 == 0);
if (isEven) {
cout