C question: off_t (and other signed integer types) minimum and maximum values

后端 未结 9 1021
耶瑟儿~
耶瑟儿~ 2020-12-06 05:58

I occasionally will come across an integer type (e.g. POSIX signed integer type off_t) where it would be helpful to have a macro for its minimum and maximum val

9条回答
  •  心在旅途
    2020-12-06 06:20

    It's technically not a macro, but in practice the following should always be folded into a constant minimum for off_t, or any signed type, regardless of sign representation. Although I'm not sure what doesn't use two's compliment, if anything.

    POSIX requires a signed integer type for off_t, so the C99 signed exact width values should be sufficient. Some platforms actually define OFF_T_MIN (OSX), but POSIX unfortunately doesn't require it.

    #include 
    #include 
    
    #include 
    
      assert(sizeof(off_t) >= sizeof(int8_t) && sizeof(off_t) <= sizeof(intmax_t));
    
      const off_t OFF_T_MIN = sizeof(off_t) == sizeof(int8_t)   ? INT8_MIN    :
                              sizeof(off_t) == sizeof(int16_t)  ? INT16_MIN   :
                              sizeof(off_t) == sizeof(int32_t)  ? INT32_MIN   :
                              sizeof(off_t) == sizeof(int64_t)  ? INT64_MIN   :
                              sizeof(off_t) == sizeof(intmax_t) ? INTMAX_MIN  : 0;
    

    The same is usable to obtain the maximum value.

      assert(sizeof(off_t) >= sizeof(int8_t) && sizeof(off_t) <= sizeof(intmax_t));
    
      const off_t OFF_T_MAX = sizeof(off_t) == sizeof(int8_t)   ? INT8_MAX    :
                              sizeof(off_t) == sizeof(int16_t)  ? INT16_MAX   :
                              sizeof(off_t) == sizeof(int32_t)  ? INT32_MAX   :
                              sizeof(off_t) == sizeof(int64_t)  ? INT64_MAX   :
                              sizeof(off_t) == sizeof(intmax_t) ? INTMAX_MAX  : 0;
    

    This could be turned into a macro using autoconf or cmake though.

提交回复
热议问题