Both are signed by default, allowing for negative and positive values.
Key takeaways:
The
int32
can store integer values ranging from -2,147,483,648 to 2,147,483,647. In contrast,int64
can store integer values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.The
int32
type uses less memory, suitable for storing smaller integers. On the other hand,int64
requires more memory and is suitable to handle larger values.
int32
and int64
are types of variables used in the C++ programming language to hold whole numbers (integers). int32
holds smaller numbers and int64
holds larger numbers. The 32
or 64
next to int
indicates how many bits of information the variable can store, which determines the range of numbers it can hold.
int32
(int
)32-bit integers can store integer values ranging from
int64
(long long
)64-bit integer data type can store integer values ranging from int32
and is used when you need to work with very large integers.
Let's write code to demonstrate the difference between int32
and int64
in C++:
#include <iostream>int main() {// int32 exampleint int32Var = 2147483647; // Maximum value for int32std::cout << "int32Var: " << int32Var << std::endl;// Attempt to exceed int32 rangeint32Var = 2147483648; // One more than the maximum value for int32std::cout << "int32Var after exceeding range: " << int32Var << std::endl; // Output will be unexpected due to overflow// int64 examplelong long int int64Var = 9223372036854775807; // Maximum value for int64std::cout << "int64Var: " << int64Var << std::endl;// Attempt to exceed int64 rangeint64Var = 9223372036854775808; // One more than the maximum value for int64std::cout << "int64Var after exceeding range: " << int64Var << std::endl; // Output will be correctreturn 0;}
Line 5: We declare an int32
variable int32Var
and assign it the maximum value for int32
(2147483647
).
Line 9: We attempt to assign int32Var
a value that is one more than the maximum value for int32
(2147483648
). This causes an overflow, and the output will be unexpected.
Line 13: Then, we declare an int64
variable int64Var
and assign it the maximum value for int64
(9223372036854775807
).
Line 17: Finally, we attempt to assign int64Var
a value one more than the maximum value for int64
(9223372036854775808
). This causes an overflow, and the output will be unexpected.
Let's summarize the key differences between int32
and int64
in the following table:
Key differences |
|
|
Size | 32 bits or 4 bytes | 64 bits or 8 bytes |
Range | -2,147,483,648 to 2,147,483,647 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Memory usage | Lower | Higher |
Use case | Suitable for smaller integers, like indexes and counts | Ideal for large numbers, financial calculations, and high-precision data |
In C++, int32
and int64
serve different purposes based on memory size and range requirements. Choosing between them depends on your specific application needs.
Haven’t found what you were looking for? Contact Us
Free Resources