Search code examples
cundefined-behavior

Is dividing an integer with value 0x80000000 an UB?


Here is the code

printf("%d", 0x80000000 / 10). It prints a correct value with respect to its absolute value, but forgets to put a minus sign. Let's check if the original integer (signed) is negative.

printf("%d", 0x80000000) is negative indeed.

However, if I wrap the literal inside a value of type integer, the division retains the sign, which is the desired behavior. Explicitly casting to int the result of division also works.

I am using clang version 18.1.5


Solution

  • 0x80000000 is not an int*1.

    0x80000000 is a positive unsigned constant. So 0x80000000 / 10 is also not negative. With an unsigned divided by an int (the 10), the int is converted to an unsigned and the quotient is also unsigned.

    printf("%d", 0x80000000 / 10) and printf("%d", 0x80000000) are problems as they attempt to print an unsigned with "%d". Use "%u" or "%x". *2


    *1 assuming an int is 32-bit or less - which is very common.

    *2 assuming an int is 32-bit.