min and max value of data type in C

后端 未结 9 1682
借酒劲吻你
借酒劲吻你 2020-11-29 17:51

What is the function to determine the min and max possible of value of datatypes (i.e, int, char.etc) in C?

9条回答
  •  萌比男神i
    2020-11-29 18:27

    To get the maximum value of an unsigned integer type t whose width is at least the one of unsigned int (otherwise one gets problems with integer promotions): ~(t) 0. If one wants to also support shorter types, one can add another cast: (t) ~(t) 0.

    If the integer type t is signed, assuming that there are no padding bits, one can use:

    ((((t) 1 << (sizeof(t) * CHAR_BIT - 2)) - 1) * 2 + 1)
    

    The advantage of this formula is that it is not based on some unsigned version of t (or a larger type), which may be unknown or unavailable (even uintmax_t may not be sufficient with non-standard extensions). Example with 6 bits (not possible in practice, just for readability):

    010000  (t) 1 << (sizeof(t) * CHAR_BIT - 2)
    001111  - 1
    011110  * 2
    011111  + 1
    

    In two's complement, the minimum value is the opposite of the maximum value, minus 1 (in the other integer representations allowed by the ISO C standard, this is just the opposite of the maximum value).

    Note: To detect signedness in order to decide which version to use: (t) -1 < 0 will work with any integer representation, giving 1 (true) for signed integer types and 0 (false) for unsigned integer types. Thus one can use:

    (t) -1 < 0 ? ((((t) 1 << (sizeof(t) * CHAR_BIT - 2)) - 1) * 2 + 1) : (t) ~(t) 0
    

提交回复
热议问题