c sharp Logo

Booleans


C++ booleans are a data type that can store two values: true or false. Booleans are used to represent logical conditions, such as whether a user has entered a valid password or whether a number is even or odd.

To declare a boolean variable in C++, you use the bool keyword. For example:

bool isLoggedIn = false;

 

This declares a boolean variable named isLoggedIn and initializes it to the value false.

You can then assign a boolean value to a variable using the assignment operator (=). For example:

isLoggedIn = true;

 

This sets the value of the isLoggedIn variable to true.

Booleans can be used in conditional statements, such as if statements and while loops. For example:

if (isLoggedIn) {

  // The user is logged in.

} else {

  // The user is not logged in.

}

 

This if statement checks the value of the isLoggedIn variable. If the variable is equal to true, the code block inside the if statement will be executed. Otherwise, the code block inside the else statement will be executed.

Booleans can also be used in logical operations, such as and, or, and not. For example:

bool hasPermission = isAdmin || isLoggedIn;

 

This statement uses the or logical operator to combine the values of the isAdmin and isLoggedIn variables. If either of the variables is equal to true, the hasPermission variable will be set to true. Otherwise, the hasPermission variable will be set to false.

Example

The following example shows how to use booleans in C++:

#include <iostream>

 

int main() {

  // Declare boolean variables.

  bool isLoggedIn = false;

  bool isAdmin = true;

 

  // Check if the user is logged in.

  if (isLoggedIn) {

    std::cout << "The user is logged in." << std::endl;

  } else {

    std::cout << "The user is not logged in." << std::endl;

  }

 

  // Check if the user is an admin.

  if (isAdmin) {

    std::cout << "The user is an admin." << std::endl;

  } else {

    std::cout << "The user is not an admin." << std::endl;

  }

 

  return 0;

}

 

Output:

The user is not logged in.

The user is an admin.

 

Booleans are a simple but powerful data type that can be used to represent logical conditions and control the flow of your program. I hope this explanation is helpful. Please let me know if you have any other questions.