A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Addition, subtraction, multiplication, division, modulo. Five operations you learned in primary school. In C, they come with caveats that primary school did not cover. Integer division truncates toward zero. Modulo with negative operands has implementation-defined sign in C89 and follows the dividend in C99. Signed overflow is undefined behavior. And operator precedence means 2 + 3 * 4 is 14, not 20. The math is familiar. The semantics are not.
#include <stdio.h>int main(void) {printf("7 / 2 = %d\n", 7 / 2);printf("7 %% 2 = %d\n", 7 % 2);printf("-7 / 2 = %d\n", -7 / 2);printf("-7 %% 2 = %d\n", -7 % 2);printf("7 / -2 = %d\n", 7 / -2);printf("7 %% -2 = %d\n", 7 % -2);printf("\n2 + 3 * 4 = %d\n", 2 + 3 * 4);printf("(2 + 3) * 4 = %d\n", (2 + 3) * 4);return 0;}
Integer division truncates toward zero. 7/2 is 3, not 3.5. -7/2 is -3, not -4. The modulo result takes the sign of the dividend in C99: -7 % 2 is -1, and 7 % -2 is 1. If you need Euclidean modulo (always non-negative), add the divisor and take modulo again: ((x % m) + m) % m.
#include <stdio.h>#include <limits.h>int main(void) {int max = INT_MAX;printf("INT_MAX = %d\n", max);printf("INT_MAX + 1 = %d\n", max + 1);int min = INT_MIN;printf("INT_MIN = %d\n", min);printf("INT_MIN - 1 = %d\n", min - 1);return 0;}
The wraparound is what happens on this platform with this compiler. The standard calls it undefined behavior. A different compiler or optimization level could produce a different result, including removing subsequent bounds checks that depend on the overflow not happening. In security-critical code, check for overflow before it happens using the limits from limits.h.
Arithmetic in C is fast and unforgiving. The hardware does the math. The language does not protect you from the consequences. Check your bounds. Know your types. Parenthesize when precedence is unclear. Next: assignment operators, the shorthand that modifies and assigns in one step.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.