The if
statement
From cppreference.com
The if
statement evaluates a condition and depending on the outcome, either executes a set of statements, or not.
It looks like this:
if (/* test */) { // statements }
And works like this:
- Run the expression /* test */, which should return true or false.
- If the result is true, run the statements in the block.
- If the result is false, skip past the block without running the statements.
For example:
if (x == 2) { y = 4; }
Does:
- Run the expression x == 2, which will return true if
x
is equal to 2, and false otherwise.- If the result is true (ie,
x
is equal to 2), run the statements in the block. So the statement y = 4 is executed. - If the result is false (ie,
x
is not equal to 2), skip past the block without running the statement.
- If the result is true (ie,
The if-else
statement
There exists a form of an if statement that executes another set of statements if the condition evaluates to false.
It looks like this:
if (/* test */) { // first block } else { //second block }
And works like this:
- Run the expression /* test */, which should return true or false.
- If the result is true, run the statements in the first block.
- If the result is false, run the statements in the second block.
For example, in the following example, z
is assigned 6 only if x
is not equal to 2.
if (x == 2) { y = 4; } else { z = 6; }
The runnable example below illustrates the if
statement:
Run this code
Output:
x is equal to 2 y: 17 y is equal to 17