-2 <1 = false. What for?

Hy! Sorry for my bad english, anyway questions:

I have this code in objective-c:

 unsigned int a = 1; int b = -2 if (b < a); 

I expect true, and if(b < a) is false instead, why?

+4
source share
5 answers

C automatically converts -2 to unsigned int into comparison. As a result, the comparison is actually (4294967294 <1), which is not so.

+9
source

You compare signed with unsigned. The signed value is raised to unsigned, resulting in a large number ( 0xFFFFFFFD , I think), which is definitely greater than 1

+7
source

For comparison, int b is used for a variable without an signed temporary variable. This means that it ends with a big one.

See the rules here: http://msdn.microsoft.com/en-us/library/3t4w2bkb(VS.80).aspx

+3
source

Put "unsigned".

If you look at the binary representation of -2 and then use this binary value as an unsigned int, then b> a

Hope this helps!

+2
source

You cannot compare signed and unsigned numbers. Most likely, unsigned gets an increased value with a sign, which leads to undefined behavior or a really large number (depending on how the negative value was stored).

0
source

Source: https://habr.com/ru/post/1335337/


All Articles