Loading lessons...
if Statements
if Statements
The if statement is how a program decides: if something is true, do this.
The basic form
C
if (condition) {
// run this code when condition is true
}A real example
C
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}Output: x is greater than y
The condition can be any truthy value
C treats 0 as false and anything non-zero as true:
C
int score = 100;
if (score) {
printf("You have points!");
}The braces are important
Without braces, only the very next statement belongs to the if:
C
if (x > y)
printf("x is greater than y"); // only this line is inside the ifTL;DR
if (condition) { ... }runs the block when the condition is true.- 0 is false; any non-zero value is true.
- Braces bundle multiple statements into the if body.
- Without braces, only the next line belongs to the if.