In this article, we will discuss the int data type in C++. It is used to store a 32-bit integer.
Some properties of the int data type are:
- Being a signed data type, it can store positive values as well as negative values.
- Takes a size of 32 bits where 1 bit is used to store the sign of the integer.
- A maximum integer value that can be stored in an int data type is typically 2, 147, 483, 647, around 231 – 1, but is compiler dependent.
- The maximum value that can be stored in int is stored as a constant in <climits> header file whose value can be used as INT_MAX.
- A minimum integer value that can be stored in an int data type is typically -2, 147, 483, 648, around -231, but is compiler dependent.
- In case of overflow or underflow of data type, the value is wrapped around. For example, if -2, 147, 483, 648 is stored in an int data type and 1 is subtracted from it, the value in that variable will become equal to 2, 147, 483, 647. Similarly, in the case of overflow, the value will round back to -2, 147, 483, 648.
Below is the program to get the highest value that can be stored in int in C++:
C++
#include <climits>
#include <iostream>
using namespace std;
int main()
{
int valueFromLimits = INT_MAX;
cout << "Value from climits "
<< "constant (maximum): " ;
cout << valueFromLimits << "\n" ;
valueFromLimits = INT_MIN;
cout << "Value from climits "
<< "constant(minimum): " ;
cout << valueFromLimits << "\n" ;
int previous = -1;
int present = 0;
while (present > previous) {
previous++;
present++;
}
cout << "\nValue using the wrap "
<< "around property:\n" ;
cout << "Maximum: " << previous << "\n" ;
cout << "Minimum: " << present << "\n" ;
return 0;
}
|
Output:
Value from climits constant (maximum): 2147483647
Value from climits constant(minimum): -2147483648
Value using the wrap around property:
Maximum: 2147483647
Minimum: -2147483648