askvity

How to Write Boolean in C++?

Published in C++ Boolean 1 min read

In C++, you write boolean values and variables using the bool keyword, along with the literal values true and false.

Declaring Boolean Variables

You declare a boolean variable much like any other data type in C++:

bool myBoolean;

This declares a variable named myBoolean that can hold either true or false.

Assigning Boolean Values

You can assign boolean values to variables in a few ways:

  • Direct Assignment:

    bool isValid = true;
    bool isFinished = false;
  • Assignment from Expressions: Boolean values are often the result of comparison or logical expressions:

    int x = 10;
    int y = 5;
    bool isGreater = (x > y); // isGreater will be true because 10 is greater than 5

Using Boolean Values

Boolean values are primarily used in conditional statements (like if, else if, else) and loops (like while, for) to control program flow.

bool isLoggedIn = true;

if (isLoggedIn) {
  std::cout << "Welcome!" << std::endl;
} else {
  std::cout << "Please log in." << std::endl;
}

Boolean Operators

C++ provides several operators that work with boolean values:

  • ! (NOT): Negates a boolean value. !true evaluates to false, and !false evaluates to true.
  • && (AND): Returns true only if both operands are true.
  • || (OR): Returns true if at least one of the operands is true.

Example:

bool hasPermission = true;
bool isAdmin = false;

if (hasPermission && isAdmin) {
  std::cout << "Access granted." << std::endl;
} else {
  std::cout << "Access denied." << std::endl;
}

if (hasPermission || isAdmin) {
  std::cout << "User has some access." << std::endl;
}

Summary

In C++, you represent boolean values using the bool type and the literals true and false. Boolean variables are crucial for controlling program flow using conditional statements and loops, and they are often the result of logical or comparison operations.

Related Articles