bhylu.com

Advertisements

C++ Booleans and If Else

Classify a route using non-overlapping thresholds and a clear invalid-input branch.

How it works

bool represents true or false. Comparisons produce boolean results, and logical operators combine conditions. An if/else-if chain chooses the first matching branch, useful for exclusive categories. Decide what should happen exactly at a threshold before selecting < or <=. A separate invalid-input branch prevents a negative duration from being classified as a wonderfully short route. Use braces even for short branches so later edits do not change which statement belongs to the rule.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror truth-conditions.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · truth-conditions.cpp

#include <iostream>

int main() {
    int minutes{45};
    if (minutes < 0) {
        std::cout << "Invalid duration\n";
    } else if (minutes <= 30) {
        std::cout << "Short round\n";
    } else if (minutes <= 60) {
        std::cout << "Standard round\n";
    } else {
        std::cout << "Split the round\n";
    }
}

Expected result

Standard round

Thirty belongs to Short and sixty belongs to Standard under this chosen policy. Only one label is produced. A proper test set includes minus one, zero, thirty, thirty-one, sixty and sixty-one. Nested rules can express dependent decisions, but deep nesting often becomes clearer when validation exits early or a named helper states a condition.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.