Joe Van Dyk wrote:

What bad things could happen if I compare signed and unsigned integers?

(is that even valid C?)

Second question first: Yes, it is valid. The operands are

subject to the "usual arithmetic conversions" (6.3.1.8), which

reconcile them to a common type. The comparison is then carried

out in that common type.

First question second: The usual arithmetic conversions may

result in a type that is surprising to the novice, changing the

"obvious" meaning of the expression:

int i = -1;

unsigned int u = i + 1;

if (u > i) ...

Clearly, u is initialized to a value greater than that of i:

after all, i is negative and u is zero, so u must be greater

than i, right? Not so, Grasshopper: after the "usual arithmetic

conversions" (which in this case convert both operands to

unsigned int), the converted i will be UINT_MAX, much *larger*

than u. If you don't understand what's happening, the result

might be a "bad thing."

--

Eric Sosman

es*****@acm-dot-org.invalid