Testing for a maximum unsigned value

后端 未结 6 1167
死守一世寂寞
死守一世寂寞 2020-12-19 17:02

Is this the correct way to test for a maximum unsigned value in C and C++ code:

if(foo == -1)
{
    // at max possible value
}

where foo is

6条回答
  •  抹茶落季
    2020-12-19 17:37

    Here's an attempt at doing this in C. It depends on the implementation not having padding bits:

    #define IS_MAX_UNSIGNED(x) ( (sizeof(x)>=sizeof(int)) ? ((x)==-1) : \
                                 ((x)==(1<

    Or, if you can modify the variable, just do something like:

    if (!(x++,x--)) { /* x is at max possible value */ }
    

    Edit: And if you don't care about possible implementation-defined extended integer types:

    #define IS_MAX_UNSIGNED(x) ( (sizeof(x)>=sizeof(int)) ? ((x)==-1) : \
                                 (sizeof(x)==sizeof(short)) ? ((x)==USHRT_MAX) : \
                                 (sizeof(x)==1 ? ((x)==UCHAR_MAX) : 42 )
    

    You could use sizeof(char) in the last line, of course, but I consider it a code smell and would typically catch it grepping for code smells, so I just wrote 1. Of course you could also just remove the last conditional entirely.

提交回复
热议问题