"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Is `long` Guaranteed to Have at Least 32 Bits in C++?

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

Published on 2024-11-07
Browse:410

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3