
Think together · Start with a story
The robot needs to record the number of players. Player counts are usually whole numbers like 1, 2, and 3—not 2.5 people.
Break down the process
- Choose a typeint
- Store data7 players
- Divide as integers7 divided by 2
- Get a result3
int stores integers within a certain range. In C++, integer division discards the fractional part by truncating toward zero.
7 / 2 gives 3. To represent a result like 3.5 people per group, use suitable floating-point arithmetic.
01What is int?
int is one of C++'s integer types. It stores whole numbers with no fractional part.
int age = 10;
int score = 95;
int temperature = -3;02How large a number can int store?
That depends on the implementation. On many modern systems, int is usually 32 bits, with a typical range of:
But the C++ standard does not require int to be 32 bits. It only requires it to represent at least the range from -32767 to 32767.
03How are positive numbers stored in binary?
The basic idea for a positive integer is to represent its value in binary.
13₁₀ = 1101₂
A real int uses a fixed number of bits to store the value.
04How are negative numbers stored?
Modern computers usually represent signed integers using two's complement.
Since C++20, the standard also specifies two's-complement representation for signed integers.
For now, remember that a negative number is not stored by simply putting a minus sign in front. It follows a specific binary encoding rule.
05Why can int not store decimals?
The rules for the int type represent integers only.
int x = 3.8;
A numeric conversion happens here. The fractional part is not stored in the int; the result is typically 3.
06Why care about the integer range?
If a calculation goes beyond the range a type can represent, an overflow problem can occur.
In C++, signed integer overflow is undefined behavior. Do not assume the value simply wraps around to the minimum.
What you have learned
intstores integers.- On many modern platforms,
intis usually 32 bits, but the standard does not require that. - Positive integers can be represented in binary; negative integers usually use two's complement.
intdoes not keep a fractional part.- Integer types have limits, and going beyond them can cause serious problems.
Next: char and bool: characters and truth values
Your turn to try
Do 5 / 2 and 5.0 / 2 have the same result in C++?
Ready? Open to see the explanation
The first uses integer division and gives 2. The second uses floating-point arithmetic and gives 2.5. Data types affect how calculations work.