C Basics · beginner · ~10 min

Operators and precedence

Use arithmetic, comparison, logical, and bitwise operators.

Lesson

C has the usual arithmetic (+ - * / %), comparison (== != < <= > >=), logical (&& || !), and bitwise (& | ^ ~ << >>) operators. Division between two integers truncates toward zero (7/2 == 3); use a double operand to get fractional results.

Precedence is mostly intuitive but has edge cases — a + b << 2 is (a+b) << 2, not a + (b<<2). When in doubt, parenthesize.

Code examples

int total = (a + b) << 2;     // bitwise shift left, ×4
int last_bit = n & 1;          // even or odd
int avg = (sum + n / 2) / n;   // round-to-nearest for positive sum

Common mistakes

  • Confusing = (assignment) with == (equality). if (x = 0) is a bug — it assigns 0 to x and then evaluates 0 as false. Modern compilers warn.
  • Short-circuit traps: in if (p && p->next), the right side is only evaluated if p is true. That's a feature — exploit it.