Skip to content

Conditions

Artemis edited this page May 13, 2023 · 2 revisions

C++ Conditions are like rules that decide when certain code should be run.

The most basic C++ Condition is called an if statement. It is used to decide if a certain block of code should be run or not, depending on if a certain condition is true.

For example:

int x = 5;
if (x > 0) {
    std::cout << "x is positive" << std::endl;
}

This code will print x is positive because x > 0 is true.

The if-else statement is used to decide between two blocks of code. If the condition is true, the first block of code will be run, and if the condition is false, the other block of code will be run.

For example:

int x = 5;
if (x > 0) {
    std::cout << "x is positive" << std::endl;
} else {
    std::cout << "x is negative" << std::endl;
}

This code will print x is positive because x > 0 is true.

The switch statement is used to decide between multiple blocks of code. You can set up different cases and depending on the result of the expression, the code in that case will be run.

For example:

int x = 5;
switch (x) {
    case 0:
        std::cout << "x is 0" << std::endl;
        break;
    case 1:
        std::cout << "x is 1" << std::endl;
        break;
    ...
    default:
        std::cout << "x is not 0 or 1" << std::endl;
        break;
}

This code will print x is not 0 or 1 because the value of x does not match any of the cases.

Clone this wiki locally