-1
这会让我抓狂:NSUInteger小于0,为什么?
NSUInteger index = -1;
if (index > 0) {
NSLog(@"Index: %d", index);
}
为什么它记录:
2013-03-14 14:31:15.418 Demo[6155:907] Index: -1
???
这会让我抓狂:NSUInteger小于0,为什么?
NSUInteger index = -1;
if (index > 0) {
NSLog(@"Index: %d", index);
}
为什么它记录:
2013-03-14 14:31:15.418 Demo[6155:907] Index: -1
???
使用格式说明符%d
会导致您的无符号整数被解析,就像它被签名一样。
变化:
NSLog(@"Index: %d", index);
到:
NSLog(@"Index: %u", index);
,它会正确显示。
或者,只要使用NSInteger
,如果您确实不需要无符号值。
问题是'整数'不知道任何有关它的签名/无符号特征。这只是一点点。 -1
与值0xFFFFFFFF是不变的。
如果它是有符号/无符号的,那么类型'知道',并且在编译时正在发出正确的处理器指令。
NSUInteger index = -1; // effectively translates to index = 0xFFFFFFFF; (all bits set)
if (index > 0) { // unsigned comparison - well, anything else than zero in unsigned comparison is bigger than zero
// so probably the JA (jump if above) asm instruction is emitted.
// if the index was NSInteger, JG will be emitted.
NSLog(@"Index: %d", index); // as others stated, you're now passing the bits of 'index' in way the NSLog treats them as signed integer
}
为什么匿名倒票,我想知道? – 2013-03-14 13:14:27
我觉得因为你不在这一点。它不应该记录任何东西,因为-1小于0.至少这是我读的。 – nickdnk 2015-07-18 14:23:35
@nickdnk:好的 - 谢谢 - 我现在看到代码有两个问题,并不能100%清楚OP所指的问题。 – 2015-07-18 14:46:15