...

/

Variable Types

Variable Types

Learn about the different types that can be stored in a variable.

C++ requires that the data type of each variable be specified before the variable is used. This lesson focuses on the basic data types—also known as primitive data types—that form the fundamental building blocks for storing data within a program. A variable’s data type determines the following: 

  • The type of data that may be stored.

  • The range of values that may be assigned.

  • The operations that may be performed on the data.

As we will see shortly, the larger the range of values allowed by the data type, the larger the memory region occupied by the variable. Can we assign the largest possible data type to each variable and simplify the coding process? No, we must not. It would be highly inefficient. C++ programs are expected to execute on physical computers that only have a finite amount of memory. Some environments, such as IoT devices, are especially resource-constrained. Therefore, it is important that we use the smallest possible data type big enough to hold the data to ensure an efficient utilization of memory. Remember, you wouldn’t buy an airplane hangar to park your motorbike.

Integers

An integer is a number that does not have any decimal places. It is a whole number. For example, 1, 2, 3, 4, etc., are all integers, but 4.3 is not. An integer can also be zero or negative. There are different integer data types available in C++. These differ in the range of values that they may hold. The following table lists these types, their sizes, and the range of values

Type of int

Bytes in memory

Range

short int

2

-32,768 to 32,767

int

4

-2,147,483,648 to 2,147,483,647

long int

4

-2,147,483,648 to 2,147,483,647

long long int

8

−9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

In some cases, the programmer would know that the integer variable would only hold positive values. In that case, we can do away with the negative numbers and extend the range of positive numbers. The following table shows how to do ...