Thuta Learning
C
BasicProgrammingBeginner

Operators

CLesson 930 min

What you'll walk away with

  • Predict the result of integer / and %, including with negative numbers
  • Explain why passed / total * 100 gives 0 because of precedence, and fix it
  • Use the short-circuit evaluation of && and || as a guard against division by zero
  • Recognise unsigned wraparound and the signed/unsigned comparison trap, and avoid them

Explain it simply

Explain it simply

Operators are the verbs of an expression: they take values and do something with them. Arithmetic operators (+ - * / %) calculate, comparison operators (== != < > <= >=) ask a question and answer 1 (true) or 0 (false), and logical operators (&& || !) combine those answers.

Assignment operators (= += -= ...) store a result back into a variable. Most of them behave exactly as in maths class, but C has a few surprises: dividing two ints throws away the fraction, and = is something completely different from ==. This lesson prepares you for those before they bite.

Problem → Why → Solution

The problem: a 90% pass rate reported as 0%

Say a dashboard shows the pass rate for 45 passed tests out of 50. In maths, 45 / 50 x 100 = 90, so you copy that formula straight into code. The compiler shows no warning at all, and the program prints Passed: 0%. The formula is right; C simply evaluates it by its own rules, not the way a maths teacher would.

pass_rate.c
int passed = 45;
int total = 50;
int percent = passed / total * 100;   /* 45 / 50 is 0, then 0 * 100 */
printf("Passed: %d%%\n", percent);     /* prints Passed: 0% */

Why does it come out as 0?

/ and * have the same precedence and group left to right, so passed / total is computed first. Both operands are ints, so 45 / 50 is integer division: the fraction of 0.9 is dropped and the result is 0. Then 0 * 100 is 0. Reordering to passed * 100 / total (giving 90), or computing in double with 100.0 * passed / total, fixes it.

Core concept: how C evaluates operators

Dividing two integers with / truncates toward zero (guaranteed since C99): 7 / 2 is 3, and -7 / 2 is -3, not -4. % gives the remainder, whose sign follows the left operand: -7 % 2 is -1. Together they always satisfy (a / b) * b + a % b == a. % works only on integers (use fmod from <math.h> for doubles), and integer division or % by zero is undefined behaviour.

When an expression mixes operators, precedence decides which runs first, and arithmetic operators of equal precedence group left to right. The table below lists them from highest to lowest. One trap is the bitwise &: it ranks below ==, so flags & 4 == 0 parses as flags & (4 == 0), and GCC's -Wall warns suggest parentheses around comparison in operand of '&'. When in doubt, add parentheses.

Comparison and logical operators produce the int 1 or 0. && and || short-circuit: if the left side already decides the result, the right side is never evaluated. That is why count != 0 && total / count > 50 is safe: when count is zero, the division simply never happens.

When types are mixed, C converts operands before computing. char and short are promoted to int first (integer promotion), and if one operand is a double the other becomes a double too. Mixing int with unsigned int turns the int into unsigned, so -1 < 10u is false (0), because -1 becomes 4294967295. Finally, x += 5 is shorthand for x = x + 5, and ++ and -- add or subtract 1, but never modify one variable twice in a single expression.

Group (high to low)Operators
Unary! - ++ -- (type)
Multiplicative* / %
Additive+ -
Relational< <= > >=
Equality== !=
Logical&& then ||
Assignment (lowest)= += -= *= /= %=
Mental model: how C reads an expression
  1. Line up operand types (convert)
  2. Highest precedence goes first
  3. Equal precedence: left to right
  4. && / || stop once the answer is known

Train yourself to think "the fraction disappears" every time you see int / int.

General pattern

c
result = a + b;     /* also - * / % */
flag = a < b;       /* also <= > >= == != : gives 1 or 0 */
both = cond1 && cond2;
either = cond1 || cond2;
opposite = !cond;
total += amount;    /* total = total + amount */
counter++;          /* counter = counter + 1 */

Arithmetic operators produce a new value; comparison and logical operators produce 1 or 0. Compound assignment (+= and friends) and ++ modify the variable in place.

Example: trying every operator group

Using x = 10 and y = 3, this program shows arithmetic, comparison, logical and compound assignment operators one at a time. Before running it, predict each line's output on paper, especially the Divide line and the one with -7.

operators.c
#include <stdio.h>

int main(void) {
  int x = 10;
  int y = 3;

  printf("Add: %d\n", x + y);
  printf("Divide: %d\n", x / y);
  printf("Remainder: %d\n", x % y);
  printf("Real divide: %.3f\n", (double)x / y);
  printf("-7 / 2 = %d, -7 %% 2 = %d\n", -7 / 2, -7 % 2);
  printf("Is x greater than y? %d\n", x > y);
  printf("x == 10 && y > 5: %d\n", x == 10 && y > 5);
  x += 5;
  printf("After x += 5: %d\n", x);
  return 0;
}

Code breakdown

  1. Lines 8-9x / y

    10 / 3 is integer division, giving 3, and 10 % 3 is the remainder 1. 3 * 3 + 1 = 10, matching the rule (a / b) * b + a % b == a.

  2. Line 10(double)x / y

    The cast converts x to double before the division, so y is converted too and the result is 3.333... Writing (double)(x / y) would convert the already-truncated 3 and print 3.000.

  3. Line 11printf("-7 / 2 = %d, -7 %% 2 = %d\n", -7 / 2, -7 % 2);

    -7 / 2 truncates toward zero to -3, and -7 % 2 takes the left operand's sign, giving -1. Inside a format string, %% prints one literal % character.

  4. Lines 12-13x == 10 && y > 5

    x > y is true, so 1. x == 10 is true but y > 5 is false, so the && gives 0. == only compares; it does not change x.

  5. Line 14x += 5;

    Shorthand for x = x + 5. x goes from 10 to 15, so the last line shows After x += 5: 15.

You should see
Add: 13
Divide: 3
Remainder: 1
Real divide: 3.333
-7 / 2 = -3, -7 % 2 = -1
Is x greater than y? 1
x == 10 && y > 5: 0
After x += 5: 15

Short-circuit, wraparound and promotion in action

In the program below count is 0, yet nothing crashes: the left side of &&, count != 0, is false, so the division on the right is skipped. Subtracting 1 from an unsigned stock of 0 does not go negative; it wraps to the largest unsigned value (4294967295 on mainstream platforms, where unsigned int is 32 bits). That wrap is defined by the standard, unlike signed int overflow. Adding two chars works on ints after promotion, so 200 comes out correctly.

operator_rules.c
#include <stdio.h>

int main(void) {
  int count = 0;
  int total = 120;
  /* && stops at the first false operand, so total / count never runs */
  printf("Safe check: %d\n", count != 0 && total / count > 50);

  unsigned int stock = 0;
  stock = stock - 1;                     /* unsigned arithmetic wraps around */
  printf("0 - 1 as unsigned: %u\n", stock);
  printf("-1 converted to unsigned: %u\n", (unsigned int)-1);

  char a = 100, b = 100;
  int sum = a + b;                       /* both chars become int first */
  printf("char 100 + char 100 = %d\n", sum);
  return 0;
}

In real projects

Where this shows up in real projects

/ and % appear wherever times and units are converted: splitting seconds into hours, minutes and seconds, or cents into dollars and cents. A ring buffer wraps its index back to the start with index = (index + 1) % SIZE, and n % 2 == 0 checks for even numbers. Pagination computes the page count as (items + per_page - 1) / per_page, a common way to make integer division round up.

Short-circuit evaluation is the backbone of guards. Production code is full of the check-then-use pattern: count != 0 && before a division, or ptr != NULL && before using a pointer (you will meet pointers in later lessons). Signed/unsigned bugs are real too: subtracting from a length of type size_t (unsigned) can produce a huge number instead of a negative one, so never ignore -Wextra's sign-compare warnings.

Common mistakes

Common mistakes

1. Writing = where you meant ==

if (x = 5) assigns 5 to x, and the assignment's value 5 is nonzero, so the condition is always true. GCC's -Wall warns suggest parentheses around assignment used as truth value. Use == to compare.

2. Comparing signed with unsigned

With int n = -1; unsigned int limit = 10;, n < limit is 0 (false) because n is converted to unsigned and becomes 4294967295. -Wextra reports comparison of integer expressions of different signedness: 'int' and 'unsigned int'. Keep both sides the same signedness.

3. Modifying one variable twice in one expression

Code such as i = i++ + 1; is undefined behaviour: i is modified by both ++ and =, and the standard does not order them. GCC warns operation on 'i' may be undefined. Split the steps into separate statements.

Best practices

Best practices

  • For ratios such as percentages, multiply before you divide (passed * 100 / total), or compute in double.
  • Add parentheses whenever precedence is in doubt; they help the next reader too.
  • Before every division, ask whether the divisor can be zero, and add a && guard if so.
  • Keep ++ and -- in statements of their own instead of burying them in complex expressions.

Mini challenge

Mini challenge: a time splitter and a score line

Write a program that splits 7384 seconds into hours, minutes and seconds, and correctly shows the pass rate for 45 passed tests out of 50. Use logical operators as well.

  • Write seconds per hour (3600) and seconds per minute (60) as enum constants
  • Compute hours, minutes and seconds with / and % only
  • Show the pass rate as an int that correctly reads 90% (use %%)
  • Print 1/0 for whether the seconds are even, and for "passed at least 40 and under 3 hours"
time_split.c
#include <stdio.h>

/* TODO: enum constants for seconds per hour and seconds per minute */

int main(void) {
  int total_seconds = 7384;
  /* TODO: hours, minutes, seconds using / and % */

  int passed = 45;
  int total = 50;

  /* TODO: print "7384 s = ? h ? min ? s" */
  /* TODO: print the pass rate (multiply before dividing) */
  /* TODO: print the even check and the && check as 1 or 0 */
  return 0;
}

Expected: The program prints these four lines: 7384 s = 2 h 3 min 4 s Score: 90% Even number of seconds? 1 Passed and under 3 h? 1

Show hint

For the minutes, first take the seconds left over after whole hours with %, then divide by 60. For the pass rate, make sure passed / total is not computed first.

Show solution
time_split.c
#include <stdio.h>

enum { SECONDS_PER_HOUR = 3600, SECONDS_PER_MINUTE = 60 };

int main(void) {
  int total_seconds = 7384;
  int hours = total_seconds / SECONDS_PER_HOUR;
  int minutes = total_seconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE;
  int seconds = total_seconds % SECONDS_PER_MINUTE;

  int passed = 45;
  int total = 50;

  printf("%d s = %d h %d min %d s\n", total_seconds, hours, minutes, seconds);
  printf("Score: %d%%\n", passed * 100 / total);
  printf("Even number of seconds? %d\n", total_seconds % 2 == 0);
  printf("Passed and under 3 h? %d\n", passed >= 40 && hours < 3);
  return 0;
}

Quick quiz 1 / 3

In C99 and later, what does printf("%d %d\n", -7 / 2, -7 % 2); print?

Quick quiz 2 / 3

Given int x = 5;, what is the value of x % 3 * 2 + 1?

Quick quiz 3 / 3

With int count = 0;, which expression never divides by zero?

What to remember

  • int / int truncates toward zero and % takes the left operand's sign (-7 / 2 = -3, -7 % 2 = -1).
  • * / % share a precedence level and group left to right, so passed / total * 100 can give 0: multiply first.
  • Comparison and logical operators give 1 or 0, and && and || short-circuit, which makes them good guards.
  • Unsigned arithmetic wraps, signed overflow is undefined, and mixed signed/unsigned comparisons are a trap.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Operators | Thuta Learning