Declare Integer Variables with Different Sizes (short, int, long)
In this step, you'll learn about different integer variable types in C++ and how to declare variables with varying memory sizes. C++ provides multiple integer types to help you choose the most appropriate storage for your data.
Open the WebIDE and create a new file called integer_variables.cpp
in the ~/project
directory:
touch ~/project/integer_variables.cpp
Add the following code to the integer_variables.cpp
file:
#include <iostream>
int main() {
// Declaring short integer (typically 2 bytes)
short smallNumber = 32767;
// Declaring standard integer (typically 4 bytes)
int regularNumber = 2147483647;
// Declaring long integer (typically 4 or 8 bytes)
long largeNumber = 9223372036854775807L;
// Printing the values of different integer types
std::cout << "Short Integer: " << smallNumber << std::endl;
std::cout << "Regular Integer: " << regularNumber << std::endl;
std::cout << "Long Integer: " << largeNumber << std::endl;
return 0;
}
Let's break down the integer types:
-
short
:
- Smallest integer type
- Typically uses 2 bytes of memory
- Range: -32,768 to 32,767
-
int
:
- Standard integer type
- Typically uses 4 bytes of memory
- Range: -2,147,483,648 to 2,147,483,647
-
long
:
- Larger integer type
- Can be 4 or 8 bytes depending on the system
- Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Compile and run the program:
g++ integer_variables.cpp -o integer_variables
./integer_variables
Example output:
Short Integer: 32767
Regular Integer: 2147483647
Long Integer: 9223372036854775807
Key points to remember:
- Choose the integer type based on the range of values you need to store
- The
L
suffix for long integers ensures proper type interpretation
- Different systems might have slightly different memory sizes for these types
Understanding integer types and their ranges is fundamental to C++ programming. These types provide different memory allocations to efficiently store various ranges of whole numbers. Let's visualize how these types fit into the broader C++ type system:
graph LR
A[C++ Data Types] --> B[Fundamental Types]
A --> C[Derived Types]
B --> D[Integer Types]
B --> E[Floating-Point Types]
B --> F[Character Types]
B --> G[Boolean]
D --> D1[short]
D --> D2[int]
D --> D3[long]
D --> D4[long long]
E --> E1[float]
E --> E2[double]
E --> E3[long double]
F --> F1[char]
F --> F2[wchar_t]
C --> H[Arrays]
C --> I[Pointers]
C --> J[References]
C --> K[std::string]
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333
style C fill:#bbf,stroke:#333
We will learn about floating-point types, character types, and boolean types in the following steps.