Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using -1 as a flag value for unsigned (size_t) types

I was using -1 as a flag value for a function whose return type is size_t (an unsigned type).

I didn't notice it at first, particularly because it wasn't causing any errors in my code (I was checking it with x == -1, not x < 0).

Are there any subtle reasons I shouldn't leave it as is? When might this behave unexpectedly? Is this commonly used?

ptrdiff_t is less common, takes longer to type, and anyway it's not really the appropriate type since the function returns an index into an array.

like image 253
dspyz Avatar asked Apr 02 '14 03:04

dspyz


1 Answers

-1 will always convert to the max unsigned value, this is due to section 4.7 Integral conversions:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

The same quote for C99 would be from 6.3.1.3:

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.49)

So we end up with:

-1 + (UMAX + 1)

which is:

UMAX
like image 157
Shafik Yaghmour Avatar answered Sep 18 '22 20:09

Shafik Yaghmour