In x86-64 linux environment, why C promote signed integer -1 to unsigned long 0xffffffffffffffff, but not 0xffffffff?

```
#include <stdio.h>
int main() {
unsigned long ul = (int)-1;
printf("%lx\n", ul);
}
```

C11 §6.3.1.3 Signed and unsigned integers ¶1,2:

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.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)}

^{60)}The rules describe arithmetic on the mathematical value, not the value of a given type of expression.

So, `-1`

is converted by adding `ULONG_MAX + 1`

, yielding `ULONG_MAX`

, as you discovered. Your system must be using 64 bits for the `unsigned long`

type.

User contributions licensed under CC BY-SA 3.0