James
James

Reputation: 43

Type conversion with unsigned operands- C

In pg 44, C programming language by K&R, at the bottom it said:

For example, suppose that int is 16 bits and long is 32 bits. Then -1L < 1U, because 1U, which is an int, is promoted to a signed long. But -1L > 1UL, because -1L is promoted to unsigned long and thus appears to be a large positive number.

I really don't know what that is talking about. I think it's comparing bits but I really don't know. Can you describe what this is talking about please?

P.S. I am really noob at C. C is my first programming language. So, can you please answer this question as easy as possible? Thank you.

Upvotes: 1

Views: 137

Answers (1)

woolstar
woolstar

Reputation: 5083

In C, the same basic bits 0xffff has two different values.

If you treat the 16-bit number as "signed" then 0xffff is -1, if it is "unsigned" then 0xffff is 65535.

When you compare a signed value with an unsigned value, the bits in the signed value get treated as "unsigned" and if the value was negative, the new value is probably not what you wanted.

Upvotes: 4

Related Questions