C usual arithmetic conversions -- last case in standard

109 views Asked by At

Trying to parse the standard, the last case seems to be the case where we have a signed and an unsigned operand, where the signed operand has larger rank, but still can't fit the full range of the unsigned operand of lower rank. This seems to be the case when we have a signed long and an unsigned int on a 32-bit architecture. The standard says the following:

Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

If I'm reading this correctly, then

long a = -3;
unsigned int b = 2;
a + b;

would cause a and b to both be converted to an unsigned long before addition? Is this correct? I don't have 32-bit machine to test on, but this would imply that a+b should have the value ULONG_MAX? Can this be right?

1

There are 1 answers

1
Grzegorz Szpetkowski On BEST ANSWER

It means exactly what you think, both operands are promoted to type unsigned long according to cited rule, see live example (ideone is apparently 32-bit):

#include <stdio.h>
#include <limits.h>

int main(void)
{
    printf("%zu\n", sizeof(int));
    printf("%zu\n", sizeof(long));

    long a = -3;
    unsigned int b = 2;

    printf("%lu\n", a + b);
    printf("%lu\n", -1UL);
    printf("%lu\n", ULONG_MAX);

    return 0;
}

Result:

4
4
4294967295
4294967295
4294967295