Module 1 · Basics
1.2Integers and floating-point numbers
Every number type in C++ has a fixed size, and that size sets what it can hold. Learn the integer and floating-point types, what happens at their limits, and how to convert between them without losing data by accident.
On this page
- Key terms
- In 30 seconds
- Integer types and their sizes
- Signed and unsigned
- Fixed-width types
- Writing number literals
- Integer division and %
- At the limits: overflow
- Floating-point numbers: float and double
- Most decimals aren’t stored exactly
- Converting between number types
- Which one should I use?
- Under the hood
- Common pitfalls
- Comparing signed and unsigned
- Subtracting from an unsigned zero
- Try it yourself
Key terms
- integer type
- A type for whole numbers:
char,short,int,longandlong long, plus the fixed-width types. sizeof- Gives the size of a type or variable in bytes, while compiling.
- byte
- The smallest piece of memory with its own address: 8 bits on this platform and almost every other.
- signed
- An integer type that holds negative and positive values.
intis signed. - unsigned
- An integer type that holds only zero and positive values, up to about twice as high.
unsigned intis an example. - fixed-width integer type
- A type from
<cstdint>with an exact size on every machine, likestd::int32_t(32 bits) orstd::uint8_t(8 bits, unsigned). std::size_t- The unsigned type the standard library uses for sizes and indexes, like the result of
.size(). - overflow
- A result too big or too small for its type. For signed types it's undefined behavior; unsigned types wrap around.
- wrap around
- Going past the largest value starts again at zero, and going below zero starts again at the largest value.
- undefined behavior
- Code the C++ rules give no meaning to. The compiler doesn't have to catch it, and the program might crash, print garbage or seem to work.
- UndefinedBehaviorSanitizer
- A checker built in with
-fsanitize=undefined. It stops the program and reports undefined behavior like signed overflow. - integer division
- Dividing two integers. The result is an integer too: the fraction is dropped.
%(remainder)- What's left over after integer division.
7 % 3is1. - floating-point type
- A type for numbers with a fractional part, stored as a binary fraction with limited precision:
floatordouble. float- A smaller floating-point type: 4 bytes on this platform, precise to about 7 decimal digits.
- rounding error
- The small difference between a decimal number and the nearest value a floating-point type can store.
std::numeric_limits- From
<limits>: tells you facts about a number type, like its smallest and largest values. - conversion
- Turning a value of one type into another type, like
intintodouble. static_cast<T>(x)- Converts
xto typeTon purpose, so readers and the compiler know you meant it. - literal
- A value written directly in the code, like
42,0.5or'G'. - suffix
- Letters after a literal that set its type:
42uis unsigned,2.5fis afloat. - two's complement
- How signed integers are stored: negative numbers count down from all bits set, so
-1is every bit set to 1.
In C++, a number lives in a fixed number of bytes, and that size limits what it can hold. A 4-byte int can count the bases in a bacterial genome but not in a human one. A double can store 0.1 only approximately. Knowing the sizes and limits of the number types tells you which one to pick, and what happens when a value doesn’t fit.
In 30 seconds
- Integer types come in several sizes;
sizeoftells you how many bytes each one uses. For an exact size, use<cstdint>types likestd::int64_t. - Unsigned integers wrap around at their limits. Signed integers that overflow are undefined behavior.
- Dividing two integers drops the fraction. Floating-point numbers keep it, but most decimals are stored only approximately.
- Braces reject conversions that lose data. Use
static_castwhen you mean to convert.
Integer types and their sizes
C++ has five basic integer types, from smallest to largest: char, short, int, long and long long. The language only sets minimum sizes, so the exact sizes depend on the machine. sizeof tells you:
#include <print>
std::println("char: {}", sizeof(char));
std::println("short: {}", sizeof(short));
std::println("int: {}", sizeof(int));
std::println("long: {}", sizeof(long));
std::println("long long: {}", sizeof(long long));Output
char: 1 short: 2 int: 4 long: 8 long long: 8
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Size |
|---|---|---|---|---|---|---|---|---|---|
char | char1 byte | 1 bytes | |||||||
short | short2 bytes | 2 bytes | |||||||
int | int4 bytes | 4 bytes | |||||||
long | long8 bytes | 8 bytes | |||||||
long long | long long8 bytes | 8 bytes | |||||||
char takes 1 byte, short 2 bytes, int 4 bytes, long 8 bytes and long long 8 bytes. These are the sizes on 64-bit Linux; on 64-bit Windows, long is 4 bytes.
These are the sizes on 64-bit Linux, which this site uses. On 64-bit Windows, long is 4 bytes. Code that depends on an exact size shouldn’t use long.
Signed and unsigned
Each integer type is signed by default: it holds negative and positive values. Put unsigned in front, and it holds only zero and up, but goes about twice as high. std::numeric_limits<T> from <limits> tells you a type’s range; ::min() and ::max() give the smallest and largest values:
#include <limits>
#include <print>
std::println("int: {} to {}", std::numeric_limits<int>::min(),
std::numeric_limits<int>::max());
std::println("unsigned int: {} to {}",
std::numeric_limits<unsigned int>::min(),
std::numeric_limits<unsigned int>::max());Output
int: -2147483648 to 2147483647 unsigned int: 0 to 4294967295
Both use the same 4 bytes, or 32 bits. A signed int spends half of its values on negative numbers.
Fixed-width types
When the exact size matters, such as for a file format, a pixel or a genome position, use the types from <cstdint>. The number in the name is the size in bits, and a u means unsigned:
#include <cstdint>
#include <limits>
#include <print>
std::uint8_t pixel{255}; // 0 to 255: one byte
std::int32_t temperature{-40}; // 4 bytes, signed
std::int64_t genome_length{3'100'000'000}; // too big for an int
std::println("{} {} {}", pixel, temperature, genome_length);
std::println("{}", std::numeric_limits<std::uint8_t>::max());Output
255 -40 3100000000 255
std::size_t is another one you’ll see often: it’s the unsigned type that sizeof and .size() return. On a 64-bit machine it’s 8 bytes.
Writing number literals
A literal is a value written in the code. You can make long ones readable and write them in other bases:
'separates digits, and the compiler ignores it:3'100'000'000.0xstarts a hexadecimal (base 16) number:0xFFis 255.0bstarts a binary (base 2) number:0b1010is 10.
#include <print>
int reads = 1'000'000;
int mask = 0xFF;
int flags = 0b1010;
std::println("{} {} {}", reads, mask, flags);Output
1000000 255 10
A suffix after a literal sets its type. Without one, a whole number is an int (or a bigger type, if it doesn’t fit in an int) and a number with a . is a double:
#include <cstddef>
#include <print>
auto a = 42; // int
auto b = 42u; // unsigned int
auto c = 42LL; // long long
auto d = 42uz; // std::size_t
auto e = 2.5; // double
auto f = 2.5f; // float
std::println("{} {} {} {} {} {}", a, b, c, d, e, f);Output
42 42 42 42 2.5 2.5
Integer division and %
When both sides of / are integers, the result is an integer too: the fraction is dropped, rounding toward zero. % gives the remainder that was left over.
#include <print>
int bases{17};
int codon_length{3};
std::println("{} codons", bases / codon_length);
std::println("{} bases left over", bases % codon_length);
std::println("{} {}", -7 / 2, -7 % 2);Output
5 codons 2 bases left over -3 -1
-7 / 2 is -3, not -4: the fraction is cut off toward zero, and the remainder has the sign of the left side.
At the limits: overflow
What happens when a result doesn’t fit depends on whether the type is signed.
Unsigned integers wrap around. Going past the largest value starts again at zero, and going below zero starts again at the largest value. This is well defined, so the same code gives the same result everywhere:
#include <limits>
#include <print>
unsigned int largest{std::numeric_limits<unsigned int>::max()};
unsigned int zero{0};
std::println("{}", largest + 1);
std::println("{}", zero - 1);Output
0 4294967295
Signed overflow is undefined behavior: the C++ rules don’t say what happens. The program might wrap, crash or behave strangely later, because the compiler is allowed to assume it never happens. UndefinedBehaviorSanitizer, which this site turns on with -fsanitize=undefined, stops the program and tells you where:
#include <limits>
#include <print>
int total{std::numeric_limits<int>::max()};
total = total + 1;
std::println("{}", total);This fails when it runs
main.cpp:5:15: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
The fix is a bigger type. If a total can pass about 2 billion, make it std::int64_t, which holds values up to about 9.2 × 1018.
Undefined behaviorSigned overflow isn't a wraparound you can rely on
Without sanitizers, the program above often prints -2147483648, which looks like a wraparound. But the compiler can also skip checks it thinks can’t fail, because it assumes the overflow never happens. Pick a type big enough for your values, and build with -fsanitize=undefined while you test.
Floating-point numbers: float and double
On this platform, double holds numbers with a fractional part, with about 15 significant decimal digits. float uses half the memory and keeps about 7:
#include <print>
float third_f = 1.0f / 3.0f;
double third_d = 1.0 / 3.0;
std::println("{} {}", sizeof(third_f), sizeof(third_d));
std::println("{}", third_f);
std::println("{}", third_d);Output
4 8 0.33333334 0.3333333333333333
Use double unless you have a reason not to. float is for large arrays where memory and speed matter more than digits, such as the weights of a neural network.
Most decimals aren’t stored exactly
Floating-point types store numbers as binary fractions. A decimal like 0.1 has no exact binary form, just as 1/3 has no exact decimal form, so it’s stored as the nearest value that fits. The small rounding errors add up:
#include <print>
double sum = 0.1 + 0.2;
std::println("{}", sum);
std::println("{}", sum == 0.3);Output
0.30000000000000004 false
To compare floating-point results, check that they’re close enough instead of equal. std::abs from <cmath> gives the size of the difference:
#include <cmath>
#include <print>
double sum = 0.1 + 0.2;
bool close = std::abs(sum - 0.3) < 1e-9;
std::println("{}", close);Output
true
1e-9 means 1 × 10-9. Pick a tolerance that fits the size of your values.
Converting between number types
C++ converts between number types for you in many places, and some of those conversions lose data. Braces refuse a conversion that loses data. A pixel holds 0 to 255, so 300 doesn’t fit:
#include <cstdint>
std::uint8_t pixel{300};The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:3:20: error: narrowing conversion of ‘300’ from ‘int’ to ‘uint8_t’ {aka ‘unsigned char’} [-Wnarrowing]
3 | std::uint8_t pixel{300};
| ^~~When you do want a conversion, write it with static_cast<T>(value). It converts value to type T, and it tells the reader you meant it:
#include <cstdint>
#include <print>
int total{7};
int count{2};
std::println("{}", total / count);
std::println("{}", static_cast<double>(total) / count);
std::println("{}", static_cast<int>(9.99));
std::println("{}", static_cast<std::uint8_t>(300));Output
3 3.5 9 44
static_cast<double>(total) / countturnstotalinto adoublefirst, so the division keeps the fraction.static_cast<int>(9.99)drops the fraction: you get9, not10.static_cast<std::uint8_t>(300)wraps: 300 is 256 + 44, and one byte keeps only the 44.
Key ideaConvert before you divide
static_cast<double>(total / count) is still 3: the integer division has already happened. Convert one side before dividing.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
int | Everyday whole numbers: counts, scores, small indexes. | It’s the natural size for the machine, and literals are int already. | int reads{0}; |
std::int64_t | Values that can pass about 2 billion: genome positions, file sizes, totals. | An int would overflow, which is undefined behavior. | std::int64_t position{3'100'000'000}; |
std::uint8_t and friends | Bytes, pixels, file formats: anywhere the exact size matters. | The size is the same on every machine. | std::uint8_t pixel{255}; |
std::size_t | Sizes and indexes from the standard library. | It’s what sizeof and .size() return, so you avoid mixing signed and unsigned. | std::size_t n{text.size()}; |
double | Any number with a fraction. | About 15 digits of precision. | double mean{0.0}; |
float | Large arrays of fractions where memory or speed matters. | Half the size of a double. | float weight{0.5f}; |
Rule of thumb: use int and double by default, a fixed-width type when the size matters, and unsigned types for bytes and bits, not for “this can’t be negative”.
Under the hood
Signed integers are stored in two’s complement: zero is all bits 0, and negative numbers count down from all bits 1. So -1 in one byte is 11111111, the same bits as 255 unsigned. In a format string, {:b} prints a number in binary and {:08b} pads it to 8 digits:
#include <cstdint>
#include <print>
std::int8_t minus_one{-1};
std::uint8_t same_bits = static_cast<std::uint8_t>(minus_one);
std::println("{:08b} {}", same_bits, same_bits);
std::println("{:08b} {}", std::uint8_t{44}, std::uint8_t{44});Output
11111111 255 00101100 44
This is why unsigned arithmetic wraps: the hardware keeps only the lowest bits of the result. 300 is 100101100 in binary, 9 bits; one byte keeps the low 8, 00101100, which is 44.
On this platform, a double is 8 bytes in the IEEE 754 format: 1 bit for the sign, 11 bits for the exponent (where the point goes), and 52 bits for the digits, in binary. With enough decimal places, you can see that 0.1 is really the nearest binary fraction:
#include <print>
std::println("{:.20f}", 0.1);Output
0.10000000000000000555
{:.20f} prints 20 digits after the point. Lesson 1.6, Printing and reading, explains format specs like these.
Common pitfalls
Comparing signed and unsigned
When you compare a signed and an unsigned integer, C++ converts the signed one to unsigned first. A negative number becomes a huge positive one, so -1 < 1u is false. GCC and Clang warn about it, so with warnings as errors it doesn’t compile:
#include <print>
#include <string>
std::string dna{"GATTACA"};
int min_length{-1};
std::println("{}", dna.size() > min_length);The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:6:31: error: comparison of integer expressions of different signedness: ‘std::__cxx11::basic_string<char>::size_type’ {aka ‘long unsigned int’} and ‘int’ [-Werror=sign-compare]
6 | std::println("{}", dna.size() > min_length);
| ~~~~~~~~~~~^~~~~~~~~~~~
cc1plus: all warnings being treated as errorsdna.size() is a std::size_t, which is unsigned. Use std::cmp_greater and std::cmp_less from <utility>, which compare the real values whatever their types:
#include <print>
#include <string>
#include <utility>
std::string dna{"GATTACA"};
int min_length{-1};
std::println("{}", std::cmp_greater(dna.size(), min_length));
std::println("{}", std::cmp_less(-1, 1u));Output
true true
Subtracting from an unsigned zero
std::size_t can’t go below zero, so size - 1 on an empty string wraps to the largest value instead of giving -1:
#include <print>
#include <string>
std::string empty{};
std::println("{}", empty.size() - 1);Output
18446744073709551615
Check that a size is greater than zero before you subtract from it.
Try it yourself
Try it yourself
This program averages the lengths of four DNA reads, but it prints 250 instead of 250.25. Fix the division. Then make total a std::int64_t, so it won’t overflow when there are millions of reads.
#include <print>
int main() {
int total{150 + 300 + 251 + 300};
int count{4};
double average = total / count;
std::println("{}", average);
}Expected output
250.25
Show a hint
Both total and count are int, so total / count drops the fraction. Convert total to double with static_cast before dividing. The total also needs a type that won't overflow for large files.
Show a solution
#include <cstdint>
#include <print>
int main() {
std::int64_t total{150 + 300 + 251 + 300};
int count{4};
double average = static_cast<double>(total) / count;
std::println("{}", average);
}static_cast<double>(total) makes the division a floating-point one, so 1001 / 4 gives 250.25 instead of 250. std::int64_t for total means adding up millions of long reads can't overflow.
Saved in this browser only.