C++:C++ If...Else Statements and Boolean Logic with Examples
C++•Conditionals

C++ If...Else Statements and Boolean Logic with Examples

Control program branching using logical conditions, relational operators, and scope-limited if statements (C++17).

Syntax

if (condition) { // branch } else { // fallback }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
conditionBoolean ExpressionExpression evaluated to true or false.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>

int main() {
    int memoryUsageMB = 650;
    int limitMB = 512;

    if (memoryUsageMB > limitMB) {
        std::cout << "[ALERT] Memory threshold exceeded: " << memoryUsageMB << "MB > " << limitMB << "MB!\n";
        std::cout << "Action: Triggering garbage collection / purge.\n";
    } else if (memoryUsageMB > limitMB * 0.8) {
        std::cout << "[WARN] Memory usage at 80% capacity.\n";
    } else {
        std::cout << "[OK] Memory footprint healthy.\n";
    }

    return 0;
}
Expected Output:
[ALERT] Memory threshold exceeded: 650MB > 512MB!
Action: Triggering garbage collection / purge.

How It Works: Step-by-Step

  • Lines 7-10: Executes first block when memory exceeds threshold limit.
  • Lines 11-12: Chained else if branch tests secondary warning threshold.

Key Concepts

  • Conditions in C++ evaluate non-zero numbers as true and 0 as false.
  • C++17 supports if (init; condition) to restrict variable lifetime to the if block.
  • Always wrap conditional blocks in braces {} for clarity.

Common Mistake: Accidental assignment inside if condition = instead of ==

if (x = 0) sets x to 0 and evaluates to false, causing subtle logic bugs.

❌ Incorrect
if (state = 1) { /* Always true and mutates state! */ }
✅ Correct
if (state == 1) { /* Clean equality test */ }

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler