Artyom Gevorgyan
Artyom Gevorgyan

Reputation: 185

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

Upvotes: 0

Views: 102

Answers (1)

chux
chux

Reputation: 154173

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.

Upvotes: 5

Related Questions