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

后端 未结 9 1025
耶瑟儿~
耶瑟儿~ 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条回答
  •  猫巷女王i
    2020-12-06 06:40

    Signed max:

    #define GENERIC_S_MAX(stype) ((stype) ((1ULL << ((sizeof(stype) * 8) - 1)) - 1ULL))
    

    Assuming your system uses two's complement, the signed min should be:

    #define GENERIC_S_MIN(stype) ((stype) -1 - GENERIC_S_MAX(stype))
    

    These should be totally portable, except that long long is technically a compiler extension in C89. This also avoids the undefined behavior of over/underflowing a signed integer.

提交回复
热议问题