Open In App

Maximum value of int in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to obtain the maximum
// value that can be store in int
#include <climits>
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    // From the constant of climits
    // header file
    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";
  
    // Using the wrap around property
    // of data types
  
    // Initialize two variables with
    // value -1 as previous and another
    // with 0 as present
    int previous = -1;
    int present = 0;
  
    // Keep on increasing both values
    // until the present increases to
    // the max limit and wraps around
    // to the negative value i.e., present
    // becomes less than previous value
    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


Last Updated : 09 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads