C If ... Else
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
You can use these conditions to perform different actions for different decisions.
C has the following conditional statements:
- Use
ifto specify a block of code to be executed, if a specified condition istrue - Use
elseto specify a block of code to be executed, if the same condition isfalse - Use
else ifto specify a new condition to test, if the first condition isfalse - Use
switchto specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of 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 test variables:
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y
(using the > operator). As x is 20 and y is 18, the condition is true, so the program prints "x is greater than y".
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) {
printf("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.
Note: Remember to include <stdbool.h> when working with bool variables.