I know, that it is well defined by the C standard that (unsigned)-1
must yield 2^n-1, i. e. an unsigned integer with all its bits set. The same goes for (uint64_t)-1ll
. However, I cannot find something in the C11 standard that specifies how (uint64_t)-1
is interpreted.
So, the question is: Is there any guarantee in the C standard, which of the following holds true?
(uint64_t)-1 == (uint64_t)(unsigned)-1 //0x00000000ffffffff
(uint64_t)-1 == (uint64_t)(int64_t)-1 //0xffffffffffffffff
Yes. See C11 6.3.1.3 Signed and unsigned integers:
1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 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.60)
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
Case 2 applies, so -1 is reduced modulo 0x10000000000000000 to yield 0xffffffffffffffff.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments