$ overview
overview/0x02·Foundations

Operators & Expressions

Arithmetic, comparison, logic, and the precedence rules that bind them.

An expression is anything that produces a value. Operators combine values into bigger expressions — C has more of these than most languages, because arithmetic, comparison, and bit manipulation all sit at the same level of the language.

Arithmetic

arithmetic.c
1int a = 17, b = 5;
2 
3a + b; // 22
4a - b; // 12
5a * b; // 85
6a / b; // 3 (integer division)
7a % b; // 2 (remainder)

%, the modulo operator, only works on integers. To get a real fractional result from division, make sure at least one side is a floating-point type:

float-division.c
1float result = a / (float)b; // 3.4

Comparison and logic

Comparisons produce an int: 1 for true, 0 for false. C has no separate boolean type in classic C (C99 added _Bool via <stdbool.h>, but plain integers work the same way and are still common).

comparisons.c
1a == b // equal to
2a != b // not equal to
3a < b // less than
4a >= b // greater than or equal to
5 
6a > 0 && b > 0 // logical AND
7a > 0 || b > 0 // logical OR
8!(a > 0) // logical NOT
warning: = is assignment, == is comparison
if (a = 5) compiles. It assigns 5 to a and the condition is always true, since 5 is nonzero. This is a classic bug — read conditions carefully, or write if (5 == a) so a typo becomes a compiler error instead.

Compound assignment and increment

shorthand.c
1int count = 0;
2 
3count += 5; // same as count = count + 5
4count -= 2;
5count *= 3;
6 
7count++; // same as count = count + 1
8count--;

count++ (postfix) returns the old value before incrementing; ++count (prefix) increments first and returns the new value. When the result isn't used in a larger expression, they behave the same — the difference only matters when you use the result immediately, like arr[i++].

Operator precedence

Multiplication and division bind tighter than addition and subtraction, and comparisons bind tighter than logical && and || — the same rules you already know from math class, extended to more operators. When in doubt, add parentheses; they cost nothing and remove all ambiguity for the next reader.

precedence.c
1int result = 2 + 3 * 4; // 14, not 20
2int clearer = 2 + (3 * 4); // same value, clearer intent