Loading lessons...
if Statements
if Statements
The if statement is how a program decides: if something is true, do this.
The basic form
if (condition) {
// run this code when condition is true
}
A real example
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:
int score = 100;
if (score) {
printf("You have points!");
}
The braces are important
Without braces, only the very next statement belongs to the if:
if (x > y)
printf("x is greater than y"); // only this line is inside the if
TL;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.