Forum

Learn C++ Boolean s…
 
Notifications
Clear all

Learn C++ Boolean statements

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

In C++, Boolean statements are all about making decisions—your code asks “Is this true?” and acts accordingly. Let’s break it down 🧠🔧


✅ What Is a Boolean?

A Boolean is a data type that can hold one of two values:

  • true (which equals 1)
  • false (which equals 0)

You declare it using the bool keyword:

bool isCodingFun = true;
bool isFishTasty = false;

🔍 Using Booleans in Conditions

Booleans are most commonly used in if statements:

bool isSunny = true;

if (isSunny) {
    std::cout << "Let's go outside!";
} else {
    std::cout << "Better stay in.";
}
  • If isSunny is true, the first block runs.
  • If it’s false, the else block runs.

🧪 Boolean Expressions

You can create Boolean values using comparison operators:

int x = 10;
std::cout << (x > 5);   // Outputs 1 (true)
std::cout << (x == 10); // Outputs 1 (true)
std::cout << (x < 3);   // Outputs 0 (false)

🔗 Logical Operators

Combine multiple Boolean expressions:

int age = 20;
bool hasTicket = true;

if (age >= 18 && hasTicket) {
    std::cout << "Welcome to the concert!";
}
  • && → AND
  • || → OR
  • ! → NOT

🧠 Boolean Conversion

C++ treats 0 as false and any non-zero value as true:

bool result = 100;  // true
bool empty = 0;     // false

You can also use std::boolalpha to print true/false instead of 1/0:

std::cout << std::boolalpha << result;  // Output: true

 


   
Quote
Share: