On 15/09/2008, at 2:15 PM, Alex Reynolds 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:

First problem: %d is for signed integers; if you want to see the value, you want %u. Second problem (which you'll see if you change the NSLog): counter is unsigned, so it *never* "turns negative".

The values of counter in your loop will be 5,4,3,2,1,0,MAX_UINT, MAX_UINT-1, etc

(Note that the range of values for unsigned integers is 0..MAX_UINT, not MAX_INT.)

However, the following does *not* run, starting from a negative integer (as I would expect):

for (NSUInteger counter = -5; counter <= 0; ++counter)
{
        NSLog(@"NSUInteger: %d", counter);
}

counter can't have a value of -5 because it's unsigned; the value you are getting here will be MAX_UINT-5. And that's not <=0, so the loop invariant fails the first time.

Also, the following works properly:

for (NSUInteger counter = 0; counter <= 5; ++counter)
{
        NSLog(@"NSUInteger: %d", counter);
}

That works properly because this time you're not assigning values that you think should be negative to an unsigned int.


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to