0

我有以下代码:

NSUInteger one = 1;
CGPoint p = CGPointMake(-one, -one);
NSLog(@"%@", NSStringFromCGPoint(p));

它的输出:

{4.29497e+09, 4.29497e+09}

另一方面:

NSUInteger one = 1;
NSLog(@"%i", -one); // prints -1

我知道可能会发生某种溢出,但是为什么这两种情况不同,为什么它不能按我想要的方式工作?即使在进行微不足道的算术运算时,我是否应该始终提醒自己变量和表达式的特定数字类型?

PS当然我可以使用unsigned int代替NSUInteger,没有区别。

4

2 回答 2

1

当您将一元应用于无符号值时,无符号值被否定,然后通过重复添加到该值来-强制返回无符号外衣。Utype_MAX + 1当您将其传递给 时CGPointMake(),该(非常大的)无符号值随后被分配给 a CGFloat

您在NSLog()语句中看不到这一点,因为您将其记录为有符号整数。将其转换回有符号整数,您确实得到-1。尝试使用NSLog("%u", -one),你会发现你又回到了4294967295.

unsigned int versus NSUInteger DOES make a difference: unsigned int is half the size of NSUInteger under an LP64 architecture (x86_64, ppc64) or when you compile with NS_BUILD_32_LIKE_64 defined. NSUInteger happens to always be pointer-sized (but use uintptr_t if you really need an integer that's the size of a pointer!); unsigned is not when you're using the LP64 model.

于 2010-09-28T06:41:15.760 回答
0

好的,实际上不知道,但是在网上阅读有关所有这些数据类型的信息,我认为问题在于从 NUSInteger(解析为 int (x32) 或 long (x64))到 CGFloat (解析为 float(x32) 或 double(x64))。

在您的第二个示例中,没有发生相同的转换。可能影响它的另一件事是,根据我的阅读,NSUinteger 的设计不包含负数,只有正数。所以这很可能是事情开始出错的地方。

于 2010-09-28T06:34:09.317 回答