c - Setting a size_t variable to -1 -
if set size_t variable -1, in:
size_t s = -1; is guaranteed contain maximal value can hold s?
for example, if sizeof(size_t) 4 bytes, can assume s 0xffffffff?
as complementary info: need implementing set, in intend use -1 'item doesn't exist'. , @ same time don't want sacrifice 0, nor using int.
yes, guaranteed become maximum, since size_t unsigned integer type, , unsigned integer types guaranteed wrap / use modulo arithmetic. c11 6.3.1.3p2 says of converting integers (-1 constant of type int) unsigned integer types.
[...] if new type unsigned, value converted repeatedly adding or subtracting 1 more maximum value can represented in new type until value in range of new type.
however, sizeof(size_t) == 4 doesn't mean has 32 bits, because sizeof tells size in bytes - i.e. chars - , char has char_bit bits. , if sizeof(size_t) * char_bit == 32, size_t can still have less 32 value bits (the rest padding bits).
p.s. i'd recommend use size_max <stdint.h> instead.
Comments
Post a Comment