C++ If-Else Statement

The if-else statement in C++ allows you to execute one block of code when a condition is true and another block when it is false. It helps handle alternative execution paths in programs.

1. Basic If-Else Statement

The if-else statement evaluates a condition and executes either the if-block or the else-block based on the condition.

C++
#include <iostream>
using namespace std;

int main() {
    int num = -5;
    if (num >= 0) {
        cout << "Number is non-negative" << endl;
    } else {
        cout << "Number is negative" << endl;
    }
    return 0;
}

2. Common Mistakes

Ensure that both if and else blocks are properly enclosed with braces when containing multiple statements to avoid logical errors.

C++
#include <iostream>
using namespace std;

int main() {
    int num = 3;
    if (num > 0)
        cout << "Positive" << endl;
        cout << "Always prints" << endl; // Misleading without braces
    else
        cout << "Negative" << endl;
    return 0;
}

Conclusion

C++ if-else statements provide a clear mechanism to handle two alternative paths in program flow. Mastering them is essential for decision-making logic in coding.