C++ If ... Else
C++ Conditions and If Statements
You already know that C++ supports familiar comparison conditions from mathematics, such as:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to: a == b
- Not equal to: a != b
These conditions are used to perform different actions depending on whether something is true or false.
C++ has the following conditional statements:
- Use
ifto specify a block of code to be executed, if a condition is true - Use
elseto specify a block of code to be executed, if the same condition is false - Use
else ifto specify a new condition to test, if the first condition is false - Use
switchto specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C++ code to be executed
if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is written in lowercase letters.
Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18.
If the condition is true, we print a message:
We can also use variables in conditions:
Example explained
In the example above, we use two variables, x and y, to test whether x is greater than y. Because 20 is greater than 18, the condition is true, and the message is printed.
Using a Boolean Variable
Since the condition in an if statement must be either true or false,
you can store the result in a boolean variable instead of writing the comparison directly:
Example
int x = 20;
int y = 18;
bool isGreater = x > y;
if (isGreater) {
cout << "x is greater than y";
}
Try it Yourself »
This can make your code easier to read, especially when the condition is complex or used more than once.