Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 171 ยท Variables and Types

Integer Types

Master C++ integers - signed vs unsigned ranges, overflow (undefined vs wrapping), signed/unsigned comparison traps, std::size_t, and hex, binary and suffixed literals.

Integers are the workhorse of almost every program: counters, indexes, IDs, sizes, prices in cents, pixel coordinates. C++ gives you a whole family of them, and it gives you a lot of control over how they behave. That control comes with sharp edges. Two rules in this lesson, about overflow and about mixing signed and unsigned values, are behind a surprising number of real-world bugs and security holes.

You already met the integer types and their sizes in Fundamental Data Types. Here you'll learn what their ranges really are, what happens when a value doesn't fit, how to avoid the signed/unsigned traps, and every way to write an integer literal.

Signed and unsigned

Every integer type comes in two flavors:

  • Signed types (int, long, std::int32_t, โ€ฆ) hold negative and positive values.
  • Unsigned types (unsigned int, std::size_t, std::uint32_t, โ€ฆ) hold only zero and positive values, but reach twice as high.

Both flavors of the same size use the same number of bits. An unsigned type spends all of them on magnitude. A signed type uses two's complement, where the top bit effectively means "negative". For n bits that gives:

Flavor Range for n bits 8 bits 32 bits
signed โˆ’2โฟโปยน โ€ฆ 2โฟโปยน โˆ’ 1 โˆ’128 โ€ฆ 127 โˆ’2,147,483,648 โ€ฆ 2,147,483,647
unsigned 0 โ€ฆ 2โฟ โˆ’ 1 0 โ€ฆ 255 0 โ€ฆ 4,294,967,295

Note the asymmetry of signed ranges: there is one more negative value than positive. That means -INT_MIN doesn't fit in an int, which matters for functions like "absolute value".

You can see the same bits read both ways:

C++ Same bits, two meanings

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 bit pattern 11110000 means 240 as unsigned and โˆ’16 as signed. Since C++20, converting an out-of-range value to a signed type is defined to work exactly like this (keep the low bits, reinterpret in two's complement). Before C++20 it was implementation-defined, though every real compiler already did the same thing.

Overflow: two very different rules

What happens when arithmetic produces a result that doesn't fit? This is where signed and unsigned part ways.

Unsigned arithmetic wraps around. It is defined to work modulo 2โฟ, like a car odometer. The maximum value plus one is zero; zero minus one is the maximum value. That is guaranteed on every platform, and hash functions and checksums rely on it.

Signed overflow is undefined behavior. If int arithmetic produces a value outside the range of int, the C++ standard places no requirement at all on what happens. It doesn't promise wraparound, a crash or an error. The compiler is allowed to assume it never happens, and optimizers really do use that assumption.

C++ Wrapping vs undefined

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 unsigned lines are exactly what the rules promise. The last line is the interesting one: on our server it prints false, even though INT_MAX + 1 would wrap to a negative number on the hardware. GCC saw x + 1 < x, reasoned that it can only be true if overflow happens, and since overflow "can't happen", replaced the whole function with return false. A different compiler, flag or surrounding code could produce a different answer. That is what undefined behavior means: the program is no longer described by the source code you wrote.

Never test for signed overflow after the fact. Checks like if (a + b < a) are themselves undefined when overflow happens, and compilers delete them. Test before you compute, as shown below. During development, compile with -fsanitize=undefined to make signed overflow a loud runtime error (see Undefined Behavior and Memory Safety).

Checking before you compute

The portable way is to compare against the limits first:

C++ A safe addition

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 (covered in Returning Values) lets the function say "no result". GCC and Clang also offer the built-ins __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow, which do the check and the arithmetic in one fast step; they are compiler extensions, not standard C++. Often the simplest fix is choosing a type that is big enough in the first place, like long long above.

Also watch for overflow in the middle of an expression. In int ms = days * 24 * 60 * 60 * 1000;, the product overflows int once days reaches 25, even if you then store it in a long long. The arithmetic happens in int because both operands are int. Make one operand wide first: days * 24LL * 60 * 60 * 1000.

The signed/unsigned trap

When you mix a signed and an unsigned operand of the same size in arithmetic or comparisons, C++ converts the signed value to unsigned. A negative number becomes a huge positive one. The results are perfectly defined, and perfectly wrong:

C++ When -1 is bigger than 3

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.

If you write the comparison balance < limit directly, it is false, and GCC warns with -Wall: "comparison of integer expressions of different signedness". Treat that warning as an error. The program above avoids it on purpose. The second problem, empty.size() - 1, produces no warning at all, and a loop like for (std::size_t i = 0; i <= v.size() - 1; ++i) on an empty vector runs about 18 quintillion times.

Habits that keep you safe:

  • Use signed int for ordinary arithmetic, even for values that "can't be negative", such as ages or quantities. A negative result is then a visible bug instead of a silent wrap to four billion.
  • Use unsigned types for bit patterns (flags, masks, hashes) and where wraparound is the point.
  • For container sizes, use std::size_t when you store or compare sizes, and range-based for loops (see for Loops) so you rarely touch indexes at all. When you need signed math on a size, use std::ssize(container).
  • For mixed comparisons, use std::cmp_less, std::cmp_equal and friends from <utility> (C++20). They always compare the true values.

std::size_t

std::size_t is the unsigned type of sizeof results and of every standard container's size(). It is big enough to hold the size of any object, so it is 64 bits on 64-bit platforms and 32 bits on 32-bit ones. It comes from <cstddef>, but almost every standard header makes it available.

Use it for indexes and sizes that come from containers, so the types match and the compiler stays quiet:

C++
std::vector<double> readings{1.5, 2.25, 3.0};
for (std::size_t i = 0; i < readings.size(); ++i) {
    std::println("reading {}: {}", i, readings[i]);
}

Its signed cousin is std::ptrdiff_t, the type you get when you subtract two pointers or iterators.

Integer literals

A literal is a value written directly in the code. C++ supports four bases:

Prefix Base Example Value
none decimal 255 255
0x or 0X hexadecimal 0xFF 255
0b or 0B binary (C++14) 0b1111'1111 255
0 octal 0377 255

The octal rule is a famous trap: a leading zero changes the base. int code = 0755; is 493, and padding a table of numbers with zeros (010, 020) silently turns them into 8 and 16. Never write leading zeros on decimal numbers.

The digit separator ' (C++14) can go anywhere between digits and is ignored by the compiler: 1'000'000, 0xFF'FF'00'00, 0b0101'1010.

Suffixes and literal types

Every literal has a type. An unsuffixed decimal literal gets the first of int, long, long long that can hold it. Hex, octal and binary literals may also become unsigned types. Suffixes let you choose:

Suffix Type Example
u or U unsigned 42u
l or L long 42L
ll or LL long long 42LL
ul, ull (any order and case) unsigned long / unsigned long long 42ULL
z / uz (C++23) signed size type / std::size_t 0uz

Prefer uppercase L; a lowercase l looks like the digit 1.

C++ Literals in every base

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.

You'll learn auto properly in Type Deduction with auto; here it just lets the compiler pick the literal's type so you can see it with sizeof. Writing 1 << 40 without the suffix would shift a 32-bit int by more than its width, which is undefined behavior; the ULL makes the shift happen in 64 bits.

A negative literal like -5 is actually the unary minus operator applied to the literal 5. You rarely notice, except that -2147483648 is not an int literal: 2147483648 doesn't fit in int, so it becomes long first. That is why <climits> defines INT_MIN as (-INT_MAX - 1).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. unsigned int u = 0; u = u - 1; What is u now (with 32-bit unsigned int)?

    Unsigned arithmetic is defined to wrap modulo 2^32, so 0 - 1 becomes the maximum value, 4,294,967,295.
  2. 2. What does the C++ standard say happens when an int addition overflows?

    Signed overflow is undefined behavior. The hardware may wrap, but the compiler can assume overflow never happens and optimize on that basis, for example by deleting overflow checks.
  3. 3. int a = -1; unsigned b = 1; Why is a < b false?

    In a mixed comparison of int and unsigned int, the signed operand is converted to unsigned. Use std::cmp_less (C++20) to compare the real values.
  4. 4. What value does int x = 012; store?

    A leading 0 makes the literal octal, and octal 12 is 1ร—8 + 2 = 10.
  5. 5. Why should you write 1ULL << 40 instead of 1 << 40?

    The shift is performed in the type of the left operand. ULL makes it a 64-bit unsigned long long, so the shift is valid.

Summary

  • Signed types hold negative values; unsigned types hold 0 to 2โฟ โˆ’ 1. Signed ranges have one extra negative value.
  • Unsigned overflow wraps (defined, modulo 2โฟ). Signed overflow is undefined behavior, and optimizers exploit that.
  • Check for overflow before computing, use a wider type, or use -fsanitize=undefined while testing.
  • Mixing signed and unsigned converts the signed value to unsigned: -1 becomes huge. Heed -Wsign-compare, and use std::cmp_less and std::ssize.
  • std::size_t is the unsigned type for sizes and indexes; prefer int for general arithmetic.
  • Literals: decimal, 0x hex, 0b binary, leading-0 octal (a trap), ' separators, and suffixes u, L, LL, uz.

Next: Floating-Point Numbers, where you'll see why 0.1 + 0.2 isn't 0.3 and how to compare decimals safely.