Geek Slack

Learn C++
    About Lesson


    C++ Booleans


    C++ Booleans

    Booleans in C++ represent truth values. They can hold either true or false. Booleans are commonly used in conditional statements and logical operations to control the flow of a program.

    1. Boolean Variables

    You can declare boolean variables using the bool keyword:

    #include <iostream>
    
    int main() {
        bool isReady = true;
        bool isFinished = false;
    
        std::cout << "isReady: " << isReady << std::endl;
        std::cout << "isFinished: " << isFinished << std::endl;
    
        return 0;
    }

    2. Comparison Operators

    Comparison operators in C++ return a boolean value (true or false):

    • ==: Equal to
    • !=: Not equal to
    • >: Greater than
    • <: Less than
    • >=: Greater than or equal to
    • <=: Less than or equal to

    Example:

    #include <iostream>
    
    int main() {
        int x = 5, y = 3;
    
        std::cout << "x == y: " << (x == y) << std::endl;
        std::cout << "x != y: " << (x != y) << std::endl;
        std::cout << "x > y: " << (x > y) << std::endl;
        std::cout << "x <= y: " << (x <= y) << std::endl;
    
        return 0;
    }

    3. Logical Operators

    Logical operators perform logical operations and return boolean results:

    • &&: Logical AND
    • ||: Logical OR
    • !: Logical NOT

    Example:

    #include <iostream>
    
    int main() {
        bool condition1 = true, condition2 = false;
    
        std::cout << "condition1 && condition2: " << (condition1 && condition2) << std::endl;
        std::cout << "condition1 || condition2: " << (condition1 || condition2) << std::endl;
        std::cout << "!condition1: " << !condition1 << std::endl;
    
        return 0;
    }

    Conclusion

    Booleans are fundamental in programming and are used extensively for decision making and controlling program flow. This chapter covered boolean variables, comparison operators, and logical operators in C++, providing you with essential tools to handle boolean logic effectively in your programs.