I\'ve encountered code that performs the following conversion:
static_cast
As far as I can tell, the C++ standard defin
From the C++11 standard, 4.7 "Integral conversions", para 2:
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).
In other words, when converting to an unsigned integer, only the value of the input matters, not its type. Converting -1 to an n-bit unsigned integer will always give you 2n-1, regardless of which integer type the -1 started as.
This is a good question and the draft C++ standard on this section 4.7
Integral conversions which says:
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).[...]
is not the most straight forward to interpret, in this case I would go back to the draft C99 standard which says:
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
where footnote 49
helpfully says:
The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
This is more straight forward and clearly gives us the result as -1 + MAX + 1
which is MAX
, regardless of what type of the operand is.