Size of int and float

后端 未结 6 841
夕颜
夕颜 2021-02-01 07:17

I have a question about the ranges of ints and floats:

If they both have the same size of 4 bytes, why do they have different ranges?

6条回答
  •  爱一瞬间的悲伤
    2021-02-01 07:43

    The standard does not specify the size in bytes, but it specifies minimum ranges that various integral types must be able to hold. You can infer minimum size in bytes from it.

    Minimum ranges guaranteed by the standard (from "Integer Types In C and C++"):

    signed char: -127 to 127
    unsigned char: 0 to 255
    "plain" char: -127 to 127 or 0 to 255 (depends on default char signedness)
    signed short: -32767 to 32767
    unsigned short: 0 to 65535
    signed int: -32767 to 32767
    unsigned int: 0 to 65535
    signed long: -2147483647 to 2147483647
    unsigned long: 0 to 4294967295
    signed long long: -9223372036854775807 to 9223372036854775807
    unsigned long long: 0 to 18446744073709551615
    

    Actual platform-specific range values are found in in C, or in C++ (or even better, templated std::numeric_limits in header).

    Standard only requires that:

    sizeof(short int) <= sizeof(int) <= sizeof(long int)

    float does not have the same "resolution" as an int despite their seemingly similar size. int is 2's complement whereas float is made up of 23 bits Mantissa, 8 bits of exponent, and 1 bit of sign.

提交回复
热议问题