C ยท Chapter 10 of 45

C Operators

Operators are symbols that perform operations on values and variables. C supports arithmetic operators (+, -, *, /, %), assignment operators (=, +=, -=), and comparison operators (==, !=, <, >).

Understanding operator precedence โ€” which operators run first โ€” is important, since it changes the result of an expression, like * running before + unless parentheses say otherwise.

Syntax
result = a + b;
if (a == b) { ... }

Arithmetic and assignment

Arithmetic operators perform math: +, -, *, /, and % (modulus, the remainder of division). Assignment operators like += and *= combine an operation with assignment in one step.

Comparison and logical

Comparison operators (==, !=, <, >, <=, >=) return 1 (true) or 0 (false). Logical operators && (AND), || (OR), and ! (NOT) combine boolean conditions.

Example 1 (c)
#include <stdio.h>

int main() {
  int a = 10, b = 3;
  printf("%d %d\n", a / b, a % b);
  return 0;
}
Output
3 1

Integer division truncates toward zero, and % gives the remainder.

Example 2 (c)
#include <stdio.h>

int main() {
  int a = 5;
  a += 3;
  printf("%d\n", a);
  printf("%d\n", (a > 5) && (a < 10));
  return 0;
}
Output
8
1

a += 3 adds 3 to a, and the logical AND expression evaluates to 1 (true).

Key points

  • % gives the remainder of integer division.
  • == tests equality; = performs assignment โ€” don't confuse them.
  • && and || combine boolean conditions; ! negates one.
  • Compound assignment operators like += shorten common patterns.
๐Ÿ’ก Note: A very common bug is writing `if (x = 5)` (assignment) instead of `if (x == 5)` (comparison).

๐Ÿ“ Quick Quiz

1. What does 10 % 3 evaluate to?

2. Which operator checks equality?

3. What does && represent?