Tag: conditionals

  • Conditionals and if Statements: Making Decisions in C++

    Conditionals and if Statements: Making Decisions in C++

    Real programs respond to situations: a value might be inside a valid range, a file might exist, a counter might have reached a limit. To react, code must branch—follow one path when a requirement holds and a different path when it doesn’t. The simplest way to create such a branch in C++ is the if statement. At runtime, the program evaluates a condition; if it’s true, the associated block runs; otherwise, execution skips past it (or takes an else path). This “choose-a-path” mechanism is the backbone of control flow in every non-trivial program.

    A first if statement

    int main() {
        int x = 7;
    
        if (x >= 0) {
            // This block runs only when x is non-negative.
            // For example, we might record that x passed a check.
        }
    
        return 0;
    }

    If the condition x >= 0 holds, the statements inside { ... } execute; otherwise they’re skipped.
    Always use braces for if blocks, even for a single statement—this avoids common mistakes when code grows.

    What is a condition?

    A condition is any expression inside if ( /* here */ ) that is evaluated and then converted to a boolean value:

    • true → take the if branch
    • false → skip it

    Comparisons (like x >= 0) already produce a boolean. C++ also allows non-boolean expressions to be converted:

    • For integers, 0 converts to false; any non-zero value converts to true.

    Prefer explicit comparisons when starting out—they read clearly.

    int n = 5;
    
    if (n != 0) {   // clearer than: if (n)
        // executes because 5 is non-zero
    }

    Overview of numeric comparison operators

    Each of these compares two numbers and yields a boolean:

    • < — less than
    • > — greater than
    • <= — less than or equal
    • >= — greater than or equal
    • == — equal to (comparison, not assignment)

    Examples:

    int a = 7, b = 10;
    
    bool r1 = (a < b);   // true
    bool r2 = (a >= b);  // false
    bool r3 = (a == 7);  // true

    Common pitfall: = assigns, == compares.
    if (a = 7) assigns 7 to a, then tests the (non-zero) result → the condition is true. That’s almost always a bug.

    Quick note on floating-point: equality (==) can be unreliable due to rounding. We will revisit robust comparisons later. For now, prefer integers in examples or use <, <=, etc.

    Adding an else branch

    Often you want an alternative when the condition is false. Computing an absolute value is a good example:

    int main() {
        int x = -12;
        int abs_x;
    
        if (x >= 0) {
            abs_x = x;
        } else {
            abs_x = -x;
        }
        // After this, abs_x == 12
    
        return 0;
    }

    The logical NOT operator !

    The operator! flips a boolean value. It also negates conditions:

    bool ready = false;
    
    if (!ready) {
        // executes because !false is true
    }
    
    int y = -3;
    if (!(y >= 0)) {   // equivalent to: if (y < 0)
        // executes because y is negative
    }

    Style tip: prefer direct, positive conditions when possible (y < 0 instead of !(y >= 0)).

    Putting it together

    Below, a simple “gate” sets a status code based on a threshold:

    int main() {
        int value = 42;
        int threshold = 50;
        int status;           // 1 = too small, 2 = ok or higher
    
        if (value < threshold) {
            status = 1;       // value did not meet the threshold
        } else {
            status = 2;       // value met or exceeded the threshold
        }
    
        bool failed_check = !(value >= threshold); 
        // true when value < threshold
    
        // After execution:
        // - status == 1
        // - failed_check == true
    
        return 0;
    }

    Key takeaways

    • if (condition) { ... } creates a branch: the block runs only when the condition is true.
    • Comparisons <, >, <=, >=, == return booleans and are the most common conditions.
    • ! negates a boolean or condition.
    • Prefer clear, direct conditions and remember: == compares, = assigns.

    Next, we’ll combine conditions with logical AND/OR (&&, ||) and build multi-branch decisions with else if—the building blocks for readable, robust control flow.