Lesson 29 +10 XP

Integer Numbers

Integer Numbers

Integers are the whole numbers: ..., -3, -2, -1, 0, 1, 2, 3, ... They're the workhorse of most programs.

Signed vs unsigned

An integer can be signed (holds negatives and positives) or unsigned (holds only zero and positive numbers):

int       // signed by default
unsigned int  // can't hold negative numbers
  • int is signed by default and can go negative.
  • unsigned gives up the negatives to get a higher positive maximum.
  • Most of the time, plain int is what you want.

How wide is an int?

The standard guarantees int is at least 16 bits, but on modern desktops it's almost always 32 bits. That gives a range of roughly -2.1 billion to +2.1 billion.

int score = 1000000000;   // fine
unsigned int big = 4000000000U;  // needs the extra room

Fixed-width integers

For exact sizes, use the <cstdint> header. These types have a guaranteed width:

#include <cstdint>

int8_t   x;   // exactly 8 bits
int16_t  y;   // exactly 16 bits
int32_t  z;   // exactly 32 bits

Each is a "fixed-width integer". The widths are exactly as named - useful when you need to know precisely how the numbers are stored.

size_t

A special unsigned type, size_t, is used for sizes and counts - like how many elements an array has. It's big enough for any count you'd realistically store:

size_t length = 10;

It's unsigned, so it can never be negative.

TL;DR

  • Integers are whole numbers; int is signed by default.
  • unsigned holds only 0 and positives, gaining a bigger maximum.
  • Modern int is 32 bits: about -2.1 billion to 2.1 billion.
  • Fixed-width types (int8_t, int32_t) have exact sizes.
  • size_t is the unsigned type for sizes and counts.