C Operators
C operators are symbols that perform operations on values and variables, such as adding numbers or comparing them. This lesson covers the operators you will use every day.
Arithmetic Operators
C has + - * / and % (remainder). Dividing two integers gives an integer: the fractional part is thrown away.
#include <stdio.h>
int main(void) {
int a = 17, b = 5;
printf("%d %d %d\n", a + b, a - b, a * b);
printf("%d %d\n", a / b, a % b);
printf("%.1f\n", (double)a / b);
return 0;
}22 12 85 3 2 3.4
Assignment and Increment
Compound operators like += and *= update a variable in place. ++ adds one and -- subtracts one. x++ uses the old value then increments; ++x increments first.
#include <stdio.h>
int main(void) {
int x = 10;
x += 5; // 15
x *= 2; // 30
int y = x++; // y = 30, x = 31
int z = ++x; // x = 32, z = 32
printf("x=%d y=%d z=%d\n", x, y, z);
return 0;
}x=32 y=30 z=32
Comparison and Logical Operators
Comparisons (== != < > <= >=) return 1 for true and 0 for false. Logical operators combine them: && (and), || (or), ! (not).
#include <stdio.h>
int main(void) {
int age = 20;
int hasTicket = 1;
printf("%d\n", age >= 18);
printf("%d\n", age >= 18 && hasTicket);
printf("%d\n", !hasTicket);
return 0;
}1 1 0
Operator Precedence
- *, / and % run before + and -.
- Comparisons run before && and ||, and && runs before ||.
- Assignment (=) has very low precedence.
- When in doubt, add parentheses: they make intent clear.
- Do not confuse = (assign) with == (compare); compile with -Wall to catch it.
Frequently asked questions
Why does 5 / 2 equal 2 in C?
Both operands are int, so C performs integer division and drops the fraction. Make one operand a double, for example 5.0 / 2, to get 2.5.
What is the difference between i++ and ++i in C?
Both add one to i. i++ evaluates to the old value, while ++i evaluates to the new value. On their own line they behave the same.
What does the % operator do in C?
It returns the remainder of integer division. For example 17 % 5 is 2. It is often used to test if a number is even (n % 2 == 0).