if and else#
int temperature = 31;
if (temperature > 30) {
printf("It's hot\n");
} else if (temperature > 20) {
printf("It's warm\n");
} else {
printf("It's cool\n");
}
The condition goes in brackets, the body in braces. C checks each condition in turn and runs the first branch that is true, then skips the rest.
Any number can be a condition: 0 is false and everything else is true. So if (count) means "if count is not zero".
Always use braces#
Braces are optional when a branch is one statement, but leaving them out invites a well-known bug:
if (x > 0)
printf("positive\n");
count++; // looks like part of the if, but always runs
Indentation means nothing to the compiler. With braces, what you see is what runs.
Combining conditions#
if (age >= 18 && has_ticket) { ... }
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { ... }
if (!found) { ... }
The ternary operator#
A compact choice between two values:
int larger = (a > b) ? a : b;
printf("%s\n", (n % 2 == 0) ? "even" : "odd");
Read it as "if a is greater than b, a, otherwise b". Keep it for short choices; nested ternaries are hard to read.
switch#
When one value is compared against many fixed alternatives, switch is tidier than a chain of else if:
switch (day) {
case 1:
printf("Monday\n");
break;
case 6:
case 7:
printf("Weekend\n");
break;
default:
printf("Weekday\n");
}
Two things to know:
breakends each case. Without it, execution falls through into the next case. That is occasionally useful, as with6and7above sharing one body, but usually a forgottenbreakis a bug.switchworks on whole numbers and characters only, not strings or doubles. For strings, useifwithstrcmp.
Comparing doubles#
Floating-point results are approximate, so never test them with ==:
double x = 0.1 + 0.2;
if (x == 0.3) { ... } // false
if (fabs(x - 0.3) < 1e-9) { ... } // true; fabs is in <math.h>
Handling the odd cases first#
Checking special cases at the top and leaving early keeps the main logic flat:
int digits(int n) {
if (n == 0) {
return 1;
}
int count = 0;
while (n != 0) {
n /= 10;
count++;
}
return count;
}
Key points#
if,else if,else: only the first true branch runs.- Zero is false; anything else is true.
- Always write braces, even around one line.
cond ? a : bchooses between two values.switchneedsbreakin each case, and only works on integers and characters.
Next: repeating work with loops.