Because NSUInteger
is an unsigned integer type. So it is when it's negated (- test
is still an unsigned integer). But since an unsigned integer cannot hold negative values, it overflows and wraps around modulo 2 to the CHAR_BIT * sizeof(NSUInteger)
th power. NSUInteger
is 32 bit long on your platform, so you will get -10 mod 4294967296
which is exactly 4294967286.
ObjC unusual behavior when casting NSUInteger to double
-
11-04-2022 - |
Pergunta
I'm experiencing some strange behavior when I negate a NSUInteger and cast to a double.
NSUInteger test = 10;
NSLog(@"%d", test);
NSLog(@"%f", (double) test);
NSLog(@"%d", -test);
NSLog(@"%f", (double) -test);
The output is:
10
10.000000
-10
4294967286.000000
Any ideas why this is the case? I'm using NSUInteger because that's what's returned from [NSArray count]. I can easily use an int instead with no problems, and I will, but I'm extremely curious as to why this is the behavior.
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow