Step 1 of 6
if and else
So far, every line of main ran every time. Real programs need to make decisions: do this if the player is alive, that if they're not. The if statement runs a block of code only when a condition is true.
if (condition) {
// runs only when condition is true
} else {
// runs only when condition is false
}
Exactly one of the two blocks runs. The else part is optional; without it, nothing happens when the condition is false.
#include <stdio.h>
int main(void) {
int temperature;
scanf("%d", &temperature);
if (temperature >= 30) {
printf("hot\n");
} else {
printf("not hot\n");
}
printf("done\n");
return 0;
}
34
hot
done
After the if/else, the program continues with the next line either way, which is why done always prints.
Comparison operators
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
< and > |
less than, greater than |
<= and >= |
less or equal, greater or equal |
A comparison produces 1 for true or 0 for false.
The = versus == trap
= assigns and == compares. if (x = 5) doesn't check whether x is 5: it stores 5 in x, and since 5 is non-zero the condition is always true. The compiler warns about this (using the result of an assignment as a condition without parentheses); when you see that warning, you almost certainly meant ==.
Your turn: read a health value and print alive if it's greater than 0, otherwise dead.