The other day, I came across this construct:
static_cast<size_type>(-1)
in some example C++ code, which is likely (depending on the details of where size_type
is from) to be equivalent to the following C:
(size_t)(-1)
As I understand it, it works based on the fact that the representation of -1 in twos complement arithmetic is 11111...1
, for as many bits as you have, so this is a quick way of getting the maximum value that an unsigned type like size_t
can hold. However, my understanding is also that C doesn't guarantee that twos complement will be used; if the C implementation uses one's complement, this will be 1 less than the the maximum value, and if it's using signed magnitude, it will be just over half the maximum value.
Is there some wrinkle that I'm missing that insures that this works right regardless of the representation of signed integers being used? Does it differ between C and C++ (many surprising things do)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…