为什么我不能比较一个新数组的计数?

时间:2021-05-24 20:42:27

Can someone explain this to me ?

有人能给我解释一下吗?

if(0 <= -1)
    NSLog(@"Thank god");
if([NSArray new].count <= -1)
    NSLog(@"What the **** ? %i", [NSArray new].count);
if([[NSArray alloc] init].count <= -1)
    NSLog(@"What the **** ? %i", [[NSArray alloc] init].count );

Output is twice What the **** ? 0 and I was expecting no output I expect to have 0 as count.

输出是***的两倍?我期望没有输出,我期望有0作为计数。

If I put the count in a int or log it it ouputs 0 (zero), but the if statement generates a true on this.

如果我把计数代入int或log它会输出0(0),但是If语句会生成一个true。

3 个解决方案

#1


6  

Problem is you are comparing a unsigned integer to signed integer.

问题是你正在比较一个无符号整数和一个有符号整数。

Little more detail. If you compare an unsigned integer to an signed integer the signed integer will be interpreted as unsigned integer. So you signed value of -1 will be intepreted as 4294967295.

更加详细的说明。如果将无符号整数与有符号整数进行比较,则有符号整数将被解释为无符号整数。所以你的值是-1将被积分为4294967295。

#2


0  

signed int i=-1;

    if(0 <= i)
        NSLog(@"Thank god");
    if([NSArray new].count <= i)
        NSLog(@"What the **** ? %i", [NSArray new].count);
    else if([[NSArray alloc] init].count <= i)
        NSLog(@"What the **** ? %i", [[NSArray alloc] init].count );

Try this.

#3


0  

This one

这一个

NSLog(@"%u", -1);

outputs 4294967295 and 0 <= 4294967295 is true.

输出4294967295,0 <= 4294967295为真。

Instead of testing for lower equals -1 try to test lower zero. It's the same. But XCode says Comparison of unsigned expression < 0 is always false so you have to do this test

不要测试低等于-1,试着测试低0。这是相同的。但是XCode说,无符号表达式< 0的比较总是错误的,所以你必须做这个测试

#1


6  

Problem is you are comparing a unsigned integer to signed integer.

问题是你正在比较一个无符号整数和一个有符号整数。

Little more detail. If you compare an unsigned integer to an signed integer the signed integer will be interpreted as unsigned integer. So you signed value of -1 will be intepreted as 4294967295.

更加详细的说明。如果将无符号整数与有符号整数进行比较,则有符号整数将被解释为无符号整数。所以你的值是-1将被积分为4294967295。

#2


0  

signed int i=-1;

    if(0 <= i)
        NSLog(@"Thank god");
    if([NSArray new].count <= i)
        NSLog(@"What the **** ? %i", [NSArray new].count);
    else if([[NSArray alloc] init].count <= i)
        NSLog(@"What the **** ? %i", [[NSArray alloc] init].count );

Try this.

#3


0  

This one

这一个

NSLog(@"%u", -1);

outputs 4294967295 and 0 <= 4294967295 is true.

输出4294967295,0 <= 4294967295为真。

Instead of testing for lower equals -1 try to test lower zero. It's the same. But XCode says Comparison of unsigned expression < 0 is always false so you have to do this test

不要测试低等于-1,试着测试低0。这是相同的。但是XCode说,无符号表达式< 0的比较总是错误的,所以你必须做这个测试