Home >Backend Development >C++ >Is `long` Guaranteed to Have at Least 32 Bits in C ?

Is `long` Guaranteed to Have at Least 32 Bits in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 17:39:301083browse

Is `long` Guaranteed to Have at Least 32 Bits in C  ?

Is long Guaranteed to Have 32 Bits?

Despite common assumptions based on the C Standard, the question arises whether long is guaranteed to have at least 32 bits. The Standard classifies the fundamental integral types as:

sizeof(char) ≤ sizeof(short int) ≤ sizeof(int) ≤ sizeof(long int)

However, many assume that based on this hierarchy, long must have 32 bits. However, the Standard explicitly states that the number of bits in a byte is implementation-defined.

Alf P. Steinbach's Claim

Despite this seeming contradiction, Alf P. Steinbach asserted that long is guaranteed to be 32 bits. He based this claim on the Implicit limit on the range of values a long can hold (LONG_MIN to LONG_MAX).

The C Standard references the C Standard (18.3.2), which defines:

LONG_MIN ≤ -2^31 + 1
LONG_MAX ≥ 2^31 - 1

Connection to 32-Bit Representation

While this establishes a range for long, it does not explicitly guarantee 32 bits. However, there are two possibilities:

  1. Twos-Complement Representation:
    If negative numbers are represented in twos-complement, storing LONG_MIN or LONG_MAX requires 32 bits.
  2. Explicit Sign Bit:
    If a sign bit is used for negative numbers, the total storage still requires 32 bits.

Conclusion

Although the C Standard does not explicitly require long to have 32 bits, the minimum range requirement (LONG_MIN to LONG_MAX) implicitly necessitates it. This is because representing these values requires either 32 bits of storage or an implementation-specific mechanism with equivalent value capacity. Therefore, it can be concluded that C guarantees that long has at least 32 bits.

The above is the detailed content of Is `long` Guaranteed to Have at Least 32 Bits in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn