Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 171 ยท Operators

Arithmetic Operators

Learn the C++ arithmetic operators + - * / %, integer vs floating-point division, the modulo operator, type promotion rules and how integer overflow bites.

Arithmetic operators look like the easiest part of any language: + adds, - subtracts, done. In C++ they hide a few rules that cause real bugs in real programs. 5 / 9 is zero. Adding two char values gives an int. Mixing a signed and an unsigned number can turn -1 into four billion. And when a signed integer overflows, the language makes no promises at all.

This lesson goes through all five arithmetic operators and the rules behind them: how the operand types decide what kind of division you get, what % is good for, how C++ converts operands before doing the math, and how to spot and avoid overflow.

The five operators

Operator Meaning Example Result
+ addition 7 + 2 9
- subtraction 7 - 2 5
* multiplication 7 * 2 14
/ division 7 / 2 3 (integers!)
% remainder (modulo) 7 % 2 1

There are also two unary forms: -x negates a value and +x returns it unchanged (it is rarely written, but it does trigger the promotions you will meet below). Unary operators bind tighter than the binary ones, so -a * b means (-a) * b.

Multiplication, division and remainder have higher precedence than addition and subtraction, and operators of the same level group left to right. So 10 - 4 - 3 is (10 - 4) - 3, which is 3, and 2 + 3 * 4 is 14. When in doubt, add parentheses: they cost nothing at run time. The full table is in Operator Precedence.

C++ The arithmetic operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Integer division versus floating-point division

The / operator does two different jobs depending on its operands:

  • If both operands are integers, it performs integer division: the result is an integer and the fractional part is discarded (truncated toward zero).
  • If at least one operand is floating point, the other is converted and you get ordinary division with a fractional result.

The type of the variable you store the result in doesn't matter. In double half = 1 / 2; the division happens first, between two ints, and produces 0. Only then is that 0 converted to 0.0.

This is the classic Fahrenheit-to-Celsius bug. The formula is C = (F โˆ’ 32) ร— 5/9, but 5 / 9 is integer division and equals 0:

C++ When division silently loses the fraction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

To get a fractional result from integer variables, convert one operand before the division: static_cast<double>(total) / count. Writing static_cast<double>(total / count) is too late, because the fraction is already gone. For literals, just write a decimal point: 5.0 / 9.

Integer division has its uses, of course: splitting items into groups, computing a page count, finding the middle index of an array. The rule for negative operands (-7 / 2 is -3) is covered in Math Functions.

Integer division by zero is undefined behavior. x / 0 and x % 0 with integers don't throw an exception; on most machines the program crashes, and an optimizing compiler may assume the divisor can never be zero and transform your code in surprising ways. Check the divisor before dividing. Floating-point division by zero is different: with the IEEE 754 doubles every mainstream platform uses, 1.0 / 0.0 gives infinity.

The remainder operator %

a % b gives what is left over after dividing a by b as integers. It only works with integer types; for double use std::fmod. It shows up constantly in everyday code:

  • Even or odd: n % 2 == 0 is true for even numbers. For odd, test n % 2 != 0, which also works for negative numbers (where the remainder is -1).
  • Every nth item: if (i % 10 == 0) runs on every tenth loop iteration.
  • Wrapping around: (index + 1) % size steps through a circular buffer and returns to 0 at the end.
  • Splitting units: seconds into minutes and seconds, cents into dollars and cents.
  • Digits: n % 10 is the last decimal digit, and n / 10 removes it.
C++ Putting % to work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that %, / and * share one precedence level and group left to right, so total_seconds % 3600 / 60 means (total_seconds % 3600) / 60.

Promotions and the usual arithmetic conversions

The arithmetic operators never work directly on small types or on two different types. Before computing, C++ converts the operands to a common type in two steps.

1. Integral promotion. Operands smaller than int (bool, char, signed char, unsigned char, short, unsigned short) are first converted to int. So adding two char values gives an int, and +c turns a char into an int, which is a short way to print a character's numeric code.

2. Usual arithmetic conversions. If the two operands still differ, the "smaller" one is converted to the "larger" one:

  • If either is a floating-point type, the other becomes that type (long double > double > float). So int + double is double.
  • Otherwise both are integers, and the one with the lower rank is converted to the higher rank (int โ†’ long โ†’ long long).
  • If one is signed and the other unsigned with the same rank, the signed one becomes unsigned. This is the dangerous rule.
C++ What type does an expression have?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last line shows the trap: -1 is converted to unsigned int before the addition, so the result is 4294967295 (the largest 32-bit unsigned value), not -1. The same thing happens with vector.size() - 1 on an empty vector, because size() returns an unsigned std::size_t. Keep signed and unsigned values apart, and see Integer Types for the details.

decltype(expression) asks the compiler for the type of an expression without evaluating it, and std::is_same_v compares two types. They are a quick way to check your understanding of these rules. You will meet both properly in Type Deduction with auto.

Integer overflow

Every integer type has a fixed range. A 32-bit int holds values from โˆ’2,147,483,648 to 2,147,483,647. What happens when a result falls outside that range depends on signedness:

  • Unsigned types wrap around: arithmetic is done modulo 2โฟ. 0u - 1 is the largest unsigned int, and adding 1 to it gives 0. This is well defined and sometimes useful (hashes, checksums).
  • Signed overflow is undefined behavior. It does not reliably "wrap to negative". The optimizer assumes it never happens, and code that relies on it can behave differently in debug and release builds.

A common trap is an overflow in an intermediate result, even when the destination is big enough:

C++
int width = 100'000;
int height = 100'000;
long long area = width * height;                         // overflow! int * int is an int
long long safe = static_cast<long long>(width) * height; // 10'000'000'000

The multiplication happens in int, overflows, and only then is the (already broken) result converted to long long. Convert one operand first, exactly like the division fix above.

When values come from users or files, check before the operation, using std::numeric_limits from <limits>:

C++ Detecting overflow before it happens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::optional (used here to say "maybe there is no result") is explained in Returning Values. GCC and Clang also offer built-ins such as __builtin_add_overflow, and C++26 adds saturating functions like std::add_sat, but the numeric_limits check works everywhere. During development, compile with -fsanitize=undefined to have signed overflow reported at run time; Undefined Behavior and Memory Safety shows how.

Floating-point arithmetic

With float and double, the operators behave like a calculator with limited precision. Results are rounded to the nearest representable value, so tiny errors appear: 0.1 + 0.2 is 0.30000000000000004. Overflow produces infinity rather than undefined behavior, and invalid operations like 0.0 / 0.0 produce NaN. Never compare computed doubles with ==; compare with a tolerance instead. All of this is the subject of Floating-Point Numbers.

C++
std::println("{}", 0.1 + 0.2);     // 0.30000000000000004
std::println("{}", 1.0 / 0.0);     // inf
std::println("{}", 1e308 * 10);    // inf

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does double r = 7 / 2; store in r?

    7 / 2 is evaluated first, with two ints, giving 3. Only then is 3 converted to the double 3.0. Write 7.0 / 2 to get 3.5.
  2. 2. Which expression correctly computes the average of the ints sum and n with a fractional part?

    The conversion must happen before the division. In the other options the integer division has already discarded the fraction.
  3. 3. What is printed by std::println("{}", -1 + 0u); on a platform with 32-bit int?

    The int -1 and the unsigned 0u have the same rank, so -1 is converted to unsigned int, becoming 4294967295, and the sum stays unsigned.
  4. 4. What is the type of 'a' + 'b'?

    Both char operands are promoted to int before the addition, so the result is an int (195 with ASCII). Characters are never concatenated by +.
  5. 5. With 32-bit int, what is true about int big = 2'000'000'000; int x = big + big;?

    Signed integer overflow is undefined behavior. It often appears to wrap on common hardware, but the compiler is allowed to assume it never happens.

Summary

  • C++ has + - * / % plus unary - and +; * / % bind tighter than + -, and equal levels group left to right.
  • With two integers, / truncates toward zero. Convert one operand before dividing (static_cast<double>(a) / b) or use a decimal literal.
  • % works only on integers and is great for even/odd checks, wrapping, splitting units and extracting digits. Test oddness with n % 2 != 0.
  • Small types are promoted to int, and mixed operands are converted to a common type. Signed mixed with unsigned becomes unsigned, which turns -1 into a huge number.
  • Unsigned overflow wraps; signed overflow is undefined behavior. Widen before multiplying and check limits with std::numeric_limits.
  • Integer division by zero is undefined behavior; floating-point division by zero gives infinity or NaN.

Next: Assignment and Increment Operators, covering +=, ++ and the difference between prefix and postfix.