C++ Long Maximum Value

In C++, a long is an integer data type used to store larger integer values compared to an int. The size of a long is typically 32 bits on most systems but can be 64 bits on others, depending on the system architecture. The maximum value a long can represent is 2,147,483,647 on a 32-bit system or 9,223,372,036,854,775,807 on a 64-bit system. This value is defined by the LONG_MAX macro in the <climits> header.


Maximum Limit of Long Data Type

The long data type represents numbers in the range:

  • Minimum Value: -2,147,483,648 (32-bit systems) or -9,223,372,036,854,775,808 (64-bit systems)
  • Maximum Value: 2,147,483,647 (32-bit systems) or 9,223,372,036,854,775,807 (64-bit systems)

The range is derived from the formula:

-2^(n-1) to 2^(n-1) - 1

Where n is the number of bits used by the data type. For a long:

  • For 32-bit systems: n = 32, resulting in -2,147,483,648 to 2,147,483,647.
  • For 64-bit systems: n = 64, resulting in -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

From this, the maximum limit of a long data type is 2,147,483,647 (32-bit systems) or 9,223,372,036,854,775,807 (64-bit systems).


C++ Program to Access Long Maximum Value

You can programmatically access the maximum value of a long using the LONG_MAX constant from the <climits> header.

The following example demonstrates how to access and use the maximum value of a long in your programs:

main.cpp

</>
Copy
#include <iostream>
#include <climits>

int main() {
    // Accessing the maximum value of long
    std::cout << "The maximum value of long is: " << LONG_MAX << std::endl;
    return 0;
}

Output in 32-bit system

The maximum value of long is: 2147483647

Output in 64-bit system

The maximum value of long is: 9223372036854775807

Explanation

  • The <climits> header provides macros for the limits of fundamental data types in C++.
  • The LONG_MAX macro defines the maximum value of a long, which depends on whether the system uses a 32-bit or 64-bit architecture.
  • The program uses std::cout to output the maximum value of a long directly using LONG_MAX.