BeginnerLesson 4 of 18
Conditions: if, switch & Operators – C
Branching, comparisons, logical operators and the ternary operator.
C has no dedicated boolean type at its core: 0 is false, everything else is true. Comparisons yield 1 or 0. You branch with if/else if/else:
#include <stdio.h>
int main(void) {
int punkte = 73;
if (punkte >= 90) {
printf("very good\n");
} else if (punkte >= 70) {
printf("good\n");
} else {
printf("needs improvement\n");
}
return 0;
}Logical operators: && (and), || (or), ! (not). They evaluate from left to right and stop as soon as the result is determined (short-circuit) – that is why p != NULL && *p > 0 is safe.
switch selects a case based on an integer value. Without break, the code continues into the next case ("fallthrough") – sometimes intended, usually a mistake.
#include <stdio.h>
int main(void) {
int tag = 3;
switch (tag) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: // Fallthrough: 3 and 4 share the code
case 4: printf("Midweek\n"); break;
default: printf("other day\n");
}
int x = 15;
printf("%s\n", (x % 2 == 0) ? "even" : "odd"); // ternary operator
printf("%d %d\n", 10 < x && x < 20, !x); // 1 0
return 0;
}WarningThe classic:
if (x = 5) is an assignment (and always true), not a comparison. You want if (x == 5). -Wall warns about it – that is why you should always enable it.TipUse parentheses deliberately in mixed expressions:
a & b == c means a & (b == c), because == binds more tightly than &. When in doubt, add parentheses.