course content

Course Content

Introduction to C++

Numerical Data TypesNumerical Data Types

For dealing with numerical data, C++ has many data types: int, float, double, short, and more. Let's find out what's the difference and which ones to use.
We can split the numerical data types of C++ into two groups:

  • Data types for whole numbers (e.g., 12);
  • Data types for floating point numbers (e.g., 0.12).

Whole numbers

The most used data type for a whole number is int. As you have seen in the previous chapter, it can only hold numbers between -2147483648 and 2147483647.

cpp

main.cpp

That happens because when you declare an int variable, it allocates precisely 4 bytes of your PC's memory. And numbers above 2147483647(or below -2147483648) do not fit inside those 4 bytes. Luckily, other data types available can allocate you more(or less) space for your needs. Here is the table:

Data TypeRangeSize
short-32,768 to 32,7672 bytes
int-2,147,483,648 to 2,147,483,6474 bytes
long-9223372036854775808 to 92233720368547758078 bytes

So you can use long to store large numbers (e.g., World's population). You can also use short if you are sure your number will not exceed the -32,768 to 32,767 range(e.g., storing a user's age). Using short will take up less space.

cpp

main.cpp

Note

Be careful with the data type you choose. If the range of a type is exceeded, the C++ compiler will not tell you this, and you will get an unexpected value without knowing something is wrong.

Floating point numbers

The data types above are designed to store whole numbers. If we tried to assign 1.6 to one of those, here is what we would get:

cpp

main.cpp

The int type ignores the decimal part of a number. The same story with short or long. To store the floating point(decimal) numbers, we should use either float or double data type.

Data TypePrecisionSize
float7 decimal digits4 bytes
double15 decimal digits8 bytes

Here is an example of using double to store 1.6.

cpp

main.cpp

Note

Since the float type only has a precision of 7 digits, the number 123.456789 is already out of its range. It can lead to inaccurate results(as shown in the example below). So it is better to use double by default unless you are sure float's precision is enough.

cpp

main.cpp

Obviously, you can use float or double to store whole numbers since those are decimal numbers with a decimal part equal to 0. However, as a good practice, if a variable stores values that can only be whole numbers (e.g., population or likes), short/int/long should be used.

cpp

main.cpp

question-icon

Suppose you want to keep track of vehicle count. Choose the data type for each of the situations:

Number of vehicles in a family:
_ _ _

Number of vehicles on a car-selling site:
_ _ _

Number of vehicles in the world:
_ _ _

Click or drag`n`drop items and fill in the blanks

dots
char
dots
long
dots
int
dots
short
down-icon

Section 2.

Chapter 3