eddie kuo
eddie kuo

Reputation: 728

Signed integer promote to unsigned long

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

Upvotes: 2

Views: 148

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

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.

Upvotes: 3

Related Questions