BETA Try the new lesson view
Theory

Questions 1–6

Answer on your own first, and only then open the answer. The code is built with the course flags.

1. What does it print?

printf("%d %.1f\n", 7 / 2, 7 / (double)2);
Answer
3 3.5

7 / 2 is two ints, so the division is integer division and the fraction is cut off. When at least one number is a double, the division is real. (Topic 2)

2. What does it print?

printf("%d\n", 17 % 5 * 2);
Answer
4

% and * have the same precedence and are worked out from the left: 17 % 5 = 2, then 2 * 2 = 4. (Topic 2)

3. What happens?

int x = 2147483647;
x = x + 1;
printf("%d\n", x);
Answer

Undefined behaviour: an int overflow. 2147483647 is the largest int (INT_MAX). On your computer you will often see -2147483648, but C doesn't promise that, and CI with UBSan stops: signed integer overflow. If you need bigger numbers, use long long. (Topic 2)

4. What does it print?

if (0.1 + 0.2 == 0.3) {
    printf("equal\n");
} else {
    printf("not equal\n");
}
Answer
not equal

0.1 and 0.2 can only be stored approximately in binary, so the sum differs from 0.3 in the last digits. Don't compare doubles with ==: check whether the difference is smaller than a small number. (Topic 2)

5. What does it print?

int i = 10;
while (i > 0) {
    i -= 3;
}
printf("%d\n", i);
Answer
-2

i: 10 → 7 → 4 → 1 → -2. The loop stops only when the condition is false, so i jumps past 0. (Topic 3)

6. Why doesn't this code build?

int x = read_int("x: ");
if (x = 5) {
    printf("five\n");
}
Answer

x = 5 is an assignment, not a comparison: it stores 5 in x, and the condition is always true. GCC warns suggest parentheses around assignment used as truth value, and -Werror turns the warning into an error. It must be x == 5. (Topic 3)