dontWatchMyProfile
dontWatchMyProfile

Reputation: 46370

Can I safely store UInt32 to NSUInteger?

In the header, it is defined like:

#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

So does an UInt32 fit without problems into an NSUInteger (an unsigned int)? Where's the difference between UInt32 and unsigned int?

And I assume that an unsigned long is bigger than an unsigned int?

Upvotes: 3

Views: 2953

Answers (2)

ohho
ohho

Reputation: 51941

You can always add some environment checking code in the initial part of your program to minimize surprise:

 if (sizeof(NSUInteger) != sizeof(UInt32)) {
     printf("Error: Wrong integer type size!\n");
     exit(0);
 }

Upvotes: 1

Dave DeLong
Dave DeLong

Reputation: 243156

I suppose the only difference between a UInt32 and an unsigned int is that a UInt32 is guaranteed to be 32 bits long, whereas an unsigned int technically could be shorter if you were running (say) on a < 32-bit operating system.

However, given that the Mac and the iPhone are both at least 32-bit systems, it's safe to use unsigned int, UInt32, and NSUInteger reasonably interchangeably. The only difference here is that a NSUInteger might be 64 bits long (on the Mac, when compiling for x86_64).

As for your question of unsigned long versus unsigned int, UInt32 is typedef'd to an unsigned long, again indicating that it's safe to use interchangeably. An unsigned long is guaranteed to be at least as big as an unsigned int.

Upvotes: 9

Related Questions