smallB
smallB

Reputation: 17148

Comparing ints gives strange results

I'm trying to get my head around usual arithmetic conversions and tried to test:

(static_cast<unsigned char>(std::numeric_limits<unsigned char>::max()) > static_cast<signed char>(-1))

this evaluates to true, which is ok, but according to Arithmetic conversion it should result in false (last bullet):

Integral promotions are performed on the operands as follows:

If either operand is of type unsigned long, the other operand is converted to type unsigned long.

If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.

If the preceding two conditions are not met, and if either operand is of type long, the other operand is converted to type long.

If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.

If none of the preceding conditions are met, both operands are converted to type int.

The last bullet says that if none of the other conditions are met both operands will be convered to type int. Following this unsigned char(max_char) will have bit pattern filled with ones only and signed char(-1) will have bit patterns filled with ones only. This would mean 1 > 1 == false, yet I'm getting the true. Any thoughts?

Upvotes: 0

Views: 75

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400682

You're right that the last bullet is the one that is used, so both operands are converted to type int. The left-hand side is (unsigned char)255, and the right-hand side is (signed char)-1. Since both 255 and -1 are representable as an int, they get converted into (int)255 and (int)-1 respectively, and since 255 is greater than -1, it returns true.

Upvotes: 3

Related Questions