Skip to content

Beginner · Operators and control flow · topic 6 of 60 · 25 min

Operators

Explanation

C has arithmetic (+ - * / %), increment and decrement (++ --), assignment (= += -=), relational (== != < > <= >=) and logical (&& || !) operators. Dividing two integers gives an integer (7 / 2 is 3, and -7 / 2 is -3). In C, 0 is false and any non-zero value is true. Modifying a variable twice in one expression, as in i = i++ + ++i, is undefined behaviour.

Arithmetic

c
printf("%d\n", 7 + 2);     // 9
printf("%d\n", 7 / 2);     // 3   (int / int: the fraction is cut off)
printf("%d\n", 7 % 2);     // 1   (remainder; only for integers)
printf("%d\n", -7 / 2);    // -3  (truncates toward zero, since C99)
printf("%d\n", -7 % 2);    // -1  (sign follows the left operand)
printf("%.1f\n", 7 / 2.0); // 3.5 (one double operand gives a double result)
Careful: Integer division silently drops the fraction. int avg = (a + b) / 2; is fine for an integer average, but double avg = (a + b) / 2; still does INTEGER division first and then stores 3.0 instead of 3.5. Make one operand a double: (a + b) / 2.0. And dividing an integer by zero is undefined behaviour (often a crash), so check divisors.

Increment and decrement

c
int i = 5;
int a = i++;    // a = 5, then i = 6   (postfix: use the old value, then add)
int b = ++i;    // i = 7, then b = 7   (prefix: add first, then use)
printf("%d %d %d\n", a, b, i);   // 5 7 7

Assignment operators

x += 5 means x = x + 5; there are also -=, *=, /=, %= and the bit operators of module 9. An assignment is itself an expression whose value is the assigned value, which is why a = b = 0; sets both, and why if (x = 5) compiles (see the next topic's warning).

True and false in C

C (before C23) has no built-in boolean keyword; any integer can be a condition. 0 means false and every non-zero value means true. Relational and logical operators produce the int 1 (true) or 0 (false). <stdbool.h> (C99) gives the names bool, true and false; in C23 they are keywords.

c
printf("%d %d\n", 5 > 3, 5 == 3);   // 1 0
int stock = 0;
if (!stock) printf("Out of stock\n");   // !0 is 1 (true)
#include <stdbool.h>
bool paid = true;

Logical operators short-circuit

c
int count = 0, total = 50;
if (count != 0 && total / count > 10) { … }   // safe: the division never runs when count is 0
if (x < 0 || x > 100) printf("out of range\n");
&& stops at the first false operand, || at the first true one.

Precedence (the important part)

Higher binds tighterOperators
1() [] -> . postfix ++ --
2unary ! ~ - + prefix ++ -- * & sizeof (type)
3* / %
4+ -
5<< >>
6< <= > >=
7== !=
8& then ^ then |
9&& then ||
10?: then = += -= …, then the comma

When in doubt, add brackets. (a & MASK) == 0 needs the brackets, because == binds tighter than &: a & MASK == 0 means a & (MASK == 0).

Undefined: changing a variable twice in one expression

c
int i = 1;
i = i++ + ++i;            // undefined behaviour: i is modified twice without sequencing
printf("%d %d\n", i, i++); // undefined: i is read and modified in the same call's arguments
Different compilers (or flags) give different answers. Split such code into separate statements.
Think of it like this: Integer division is like sharing 7 rotis between 2 people without tearing any: each gets 3, and 1 remains (the % result). To get 3.5 each you must allow tearing: use doubles.
Tip: Compile with -Wall: gcc warns about "operation on 'i' may be undefined" and about suspicious precedence like a & b == c.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Operators · 1/6

Operators

In this lesson you will calculate and compare with C operators.

Prefer a video by a teacher? Find free videos on “c operators integer division increment precedence tutorial” on YouTube ↗

In real life: Packing laddoos into boxes

A sweet shop packs laddoos 12 to a box. For an order of 150, the shop's billing program uses / to get full boxes and % to get the loose pieces.

c
#include <stdio.h>

int main(void) {
    int order = 150, per_box = 12;
    printf("%d boxes and %d loose\n", order / per_box, order % per_box);
    return 0;
}
Prints 12 boxes and 6 loose.

Practice (0/3 done)

Task 1 · Question

What does this print? int x = 10; int y = x++ + 5; printf("%d %d\n", x, y);

Task 2 · Question

What does this print? int a = 5, b = 2; double r = a / b; printf("%.1f\n", r);

Task 3 · Code · Javascript

C integer division truncates toward zero. JavaScript has no integer type, so write cDiv(a, b) and cMod(a, b) that return exactly what C's a / b and a % b give for ints (assume b is not 0).

Quick quiz

Question 1

1.What is 17 % 5 in C?

Question 2

2.What value does (3 < 5) have in C?

Question 3

3.In a && b, when is b not evaluated?

Question 4

4.Which expression is undefined behaviour?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is 17 % 5 in C?

Answer: 2

5 × 3 = 15, remainder 2.

What value does (3 < 5) have in C?

Answer: 1

Comparisons produce the int 1 or 0.

In a && b, when is b not evaluated?

Answer: When a is 0

If a is false, the result is already false.

Which expression is undefined behaviour?

Answer: i = i++ + 1

i is modified twice without sequencing.

Integer.MAX_VALUE + 1 gives…Related

Answer: Integer.MIN_VALUE (-2147483648)

int overflow wraps around silently.

From Operators and expressions

int a = 7; int b = (a % 2 == 0) ? 1 : 0; What is b?Related

Answer: 0

7 % 2 is 1, so the condition is false and b gets 0.

From Operators and decisions: if, else and switch

What does _ mean in a switch expression?Related

Answer: Match anything else (the discard)

The discard pattern _ matches any value not matched earlier.

From Decisions: if, else, switch and switch expressions

Is it legal to compute a + n for int a[n]?Related

Answer: Yes, one past the end may be computed but not dereferenced

The one-past-the-end rule.

From Pointer arithmetic

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Operators and control flow” before its exam: Type conversion and casting, Decisions: if, else and switch, Loops: for, while and do-while, Solving problems with loops.
  2. Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and arrays. 60 topics left in the course before the final exam.

← Previous: Input and output: printf and scanf