Course Content
C++ Data Types
C++ Data Types
Integers
To store integers (whole numbers), you can use the int
data type.
main
#include <iostream> int main() { int num = 1231; // Printing the number stored in num std::cout << "The value of num is: " << num; }
As we said in the previous chapter, we specify the type of variable to inform the computer how much memory to allocate for holding it. To hold the int
variable, the computer allocates 4 bytes.
Now, you can access the variable using its name (num
in the above example), reassign its value, and perform mathematical operations on the num
variable.
main
#include <iostream> int main() { int num = 1231; std::cout << "Initial value: " << num << std::endl; num = 150; std::cout << "New value: " << num << std::endl; num = num + 50; std::cout << "New value + 50: " << num << std::endl; }
If you reassign the value of a variable, then the value in memory is overwritten.
You may have noticed that so far, all the values we assigned to int
(1231, 150, 200) are less than 16 symbols in binary code, so they could be stored in two cells (bytes). However, the int
data type always takes up 4 bytes. The unused space in memory is filled with zeros.
It is not a big problem when the value takes less space than the int
type can store. Still, as we will soon, we can sometimes make it more memory-efficient by using only 2 bytes.
The real trouble begins when the value takes more than 4 bytes. In this case, we just cannot use the int
type to store it.
Therefore, we can only use the int
type for numbers that fit in 4 bytes. The range of values that fit in 4 bytes is from -2147483648 to 2147483647.
Note
If the number exceeds -2,147,483,648 to 2,147,483,647 range, we must not use the
int
data type for storing it.
Thanks for your feedback!