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
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)