It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form is:
1 2 3 | if (condition) statement |
where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues on the next instruction after the conditional structure.
For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:
1 2 3 4 | if (x == 100) cout << "x is 100"; |
If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:
1 2 3 4 5 6 7 | if (x == 100) { cout << "x is "; cout << x; } |
We can additionally specify what we want that happens if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:
1 2 3 | if (condition) statement1 else statement2 |
For example:
1 2 3 4 5 6 | if (x == 100) cout << "x is 100"; else cout << "x is not 100"; |
prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the present value stored in x is positive, negative or none of the previous, that is to say, equal to zero.
1 2 3 4 5 6 7 8 | if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; |
Remember that in case we want more than a single instruction to be executed, we must group them in a block of instructions by using curly brackets { }.