C++ - If Condition

In C++, the if...else statement is used for conditional branching, allowing you to execute different blocks of code based on a certain condition. Here are the different forms of the if...else statement:

The if Statement:

The if statement is used to conditionally execute a block of code if a given condition is true. It has the following syntax:

if (condition) {
    // Code to be executed if the condition is true
}

Example:

int num = 10;
if (num > 0) {
    std::cout << "The number is positive." << std::endl;
}

The else Statement:

The else statement is used in conjunction with the if statement. It allows you to specify an alternative block of code to be executed when the if condition is false. It has the following syntax:

if (condition) {
    // Code to be executed if the condition is true
} else {
    // Code to be executed if the condition is false
}

Example:

int num = -5;
if (num > 0) {
    std::cout << "The number is positive." << std::endl;
} else {
    std::cout << "The number is non-positive." << std::endl;
}

The else if Statement:

The else if statement allows you to specify additional conditions to be checked if the previous if condition and the preceding else if conditions are false. It can be used multiple times within an if...else block. It has the following syntax:

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if all conditions are false
}

Example:

int num = 0;
if (num > 0) {
    std::cout << "The number is positive." << std::endl;
} else if (num < 0) {
    std::cout << "The number is negative." << std::endl;
} else {
    std::cout << "The number is zero." << std::endl;
}

Short Hand If...Else (Ternary Operator):

The ternary operator (?:) provides a compact way to write a simple conditional expression in a single line. It evaluates a condition and returns one of two expressions depending on the condition's result. It has the following syntax:

(condition) ? expression1 : expression2

If the condition is true, expression1 is evaluated and returned; otherwise, expression2 is evaluated and returned.

Example:

int num = 10;
std::string result = (num > 0) ? "Positive" : "Non-positive";
std::cout << "The number is " << result << std::endl;

In this example, if num is greater than 0, "Positive" is assigned to the variable result; otherwise, "Non-positive" is assigned.