Re: NSUInteger in for-loop?
Re: NSUInteger in for-loop?
- Subject: Re: NSUInteger in for-loop?
- From: Graff <email@hidden>
- Date: Mon, 15 Sep 2008 01:32:47 -0400
On Sep 14, 2008, at 9:15 PM, Alex Reynolds <email@hidden>
wrote:
I'm wondering if I'm using unsigned integers (specifically NSUInteger)
properly or not.
I was under the impression that unsigned integers run from 0 to
MAX_INT, but when I use them in a "for" loop within these bounds, the
loop does not seem to always obey these constraints.
For example:
for (NSUInteger counter = 5; counter >= 0; --counter)
{
NSLog(@"NSUInteger: %d", counter);
}
keeps running well after the "counter" variable turns negative:
2008-09-14 21:03:12.056 NSUIntTest[19579:10b] NSUInteger: 5
2008-09-14 21:03:12.059 NSUIntTest[19579:10b] NSUInteger: 4
2008-09-14 21:03:12.063 NSUIntTest[19579:10b] NSUInteger: 3
2008-09-14 21:03:12.068 NSUIntTest[19579:10b] NSUInteger: 2
2008-09-14 21:03:12.072 NSUIntTest[19579:10b] NSUInteger: 1
2008-09-14 21:03:12.077 NSUIntTest[19579:10b] NSUInteger: 0
2008-09-14 21:03:12.081 NSUIntTest[19579:10b] NSUInteger: -1
2008-09-14 21:03:12.085 NSUIntTest[19579:10b] NSUInteger: -2
First of all, unsigned int ranges from 0 to UINT_MAX. NSUInteger
ranges from 0 to NSUIntegerMax, int ranges from INT_MIN TO INT_MAX.
These are defined in limits.h.
Secondly, as Nathan said you are using the incorrect format
specifier. When you use %d it will interpret the bit pattern passed
in as if it were a signed integer.
When you decrement an unsigned integer (or a NSUInteger) it will wrap-
around at 0. This means that decrementing 0 by 1 will set your value
at the maximum value for your variable type. This corresponds to the
same bit pattern as a value of -1 for a signed integer. Thus since
you are displaying the unsigned integer as a signed integer you see
-1, -2, -3, ...
Last, when you run your loop you are ending your loop when counter is
less than 0. Since an unsigned integer can never be less than 0 you
get an infinite loop. You should either be using a signed integer and
break when counter is less than 0 or use a signed integer and break
when counter equals 0, accounting for the fact that you'll get 1 less
run through the loop.
Hope this helps!
- Graff
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden