Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUInteger vs NSInteger, int vs unsigned, and similar cases

Anyone have the expertise to explain when to use NSUInteger and when to use NSInteger?

I had seen Cocoa methods returning NSInteger even in cases where the returned value will always be unsigned.

What is the fundamental reason? Is NSInteger or int strictly limited to if we want to represent negative value?

From NSObjCRuntime.h:

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endif 
like image 734
Jesse Armand Avatar asked Mar 31 '10 23:03

Jesse Armand


People also ask

What is NSUInteger?

Describes an unsigned integer.

What is an unsigned int?

An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation. The most significant byte is 0 and the least significant is 3.

Is int the same as unsigned?

An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.


1 Answers

You should also be aware of integer conversion rules when dealing with NSUInteger vs. NSInteger:

The following fragment for example returns 0 (false) although you'd expect it to print 1 (true):

NSInteger si = -1; NSUInteger ui = 1; printf("%d\n", si < ui); 

The reason is that the [si] variable is being implicitly converted to an unsigned int!

See CERT's Secure Coding site for an in-depth discussion around these 'issues' and how to solve them.

like image 164
Erik Abele Avatar answered Sep 20 '22 09:09

Erik Abele