Testing for a maximum unsigned value

后端 未结 6 1146
死守一世寂寞
死守一世寂寞 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:33

    I suppose that you ask this question since at a certain point you don't know the concrete type of your variable foo, otherwise you naturally would use UINT_MAX etc.

    For C your approach is the right one only for types with a conversion rank of int or higher. This is because before being compared an unsigned short value, e.g, is first converted to int, if all values fit, or to unsigned int otherwise. So then your value foo would be compared either to -1 or to UINT_MAX, not what you expect.

    I don't see an easy way of implementing the test that you want in C, since basically using foo in any type of expression would promote it to int.

    With gcc's typeof extension this is easily possible. You'd just have to do something like

    if (foo == (typeof(foo))-1)
    

提交回复
热议问题