How are boolean variables declared in C++?

0192

In C++, boolean variables are declared using the bool data type. Here’s how to do it:

Declaration Syntax:

  1. Basic Declaration:

    bool isStudent; // Declares a boolean variable
    
  2. Initialization: You can also initialize a boolean variable at the time of declaration:

    bool isStudent = true;  // Initialized to true
    bool hasPassedExam = false; // Initialized to false
    
  3. Multiple Declarations: You can declare and initialize multiple boolean variables in a single statement:

    bool isStudent = true, hasPassedExam = false;
    

Example Code:

#include <iostream>

int main() {
    bool isStudent = true;       // Declaring and initializing
    bool hasPassedExam = false;  // Declaring and initializing

    std::cout << "Is Student: " << std::boolalpha << isStudent << std::endl;
    std::cout << "Passed Exam: " << hasPassedExam << std::endl;

    return 0;
}

Output:

Is Student: true
Passed Exam: false

Summary:

Boolean variables in C++ are declared using the bool keyword, and they can be initialized to true or false. This allows for effective representation of binary states in your programs. If you have further questions or need clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!