if, NSInteger, NSUInteger = weird comparison result

Discussion in 'iOS Programming' started by HARDWARRIOR, May 28, 2009.

  1. HARDWARRIOR macrumors member

    Joined:
    Nov 17, 2008
    #1
    Hi
    Very simple code:
    Code:
    NSUInteger u = 0;
        NSInteger i = 3;
        
        for (NSInteger t = 0; t < 5; t++) {
            u ++;
            NSLog(@"u = %d i = %d", u, i);
            NSLog(@"i - u = %d", i - u);
            if (i - u > 1)
                NSLog(@"bang!");
            NSLog(@"==============");
        }
    
    gives weird result in last 2 iterations:
    Code:
    2009-05-28 19:26:37.168 weirdComparison[15723:20b] u = 1 i = 3
    2009-05-28 19:26:37.170 weirdComparison[15723:20b] i - u = 2
    2009-05-28 19:26:37.170 weirdComparison[15723:20b] bang!
    2009-05-28 19:26:37.171 weirdComparison[15723:20b] ==============
    2009-05-28 19:26:37.172 weirdComparison[15723:20b] u = 2 i = 3
    2009-05-28 19:26:37.172 weirdComparison[15723:20b] i - u = 1
    2009-05-28 19:26:37.172 weirdComparison[15723:20b] ==============
    2009-05-28 19:26:37.173 weirdComparison[15723:20b] u = 3 i = 3
    2009-05-28 19:26:37.173 weirdComparison[15723:20b] i - u = 0
    2009-05-28 19:26:37.173 weirdComparison[15723:20b] ==============
    2009-05-28 19:26:37.174 weirdComparison[15723:20b] u = 4 i = 3
    2009-05-28 19:26:37.175 weirdComparison[15723:20b] i - u = -1
    2009-05-28 19:26:37.176 weirdComparison[15723:20b] bang!
    2009-05-28 19:26:37.176 weirdComparison[15723:20b] ==============
    2009-05-28 19:26:37.176 weirdComparison[15723:20b] u = 5 i = 3
    2009-05-28 19:26:37.177 weirdComparison[15723:20b] i - u = -2
    2009-05-28 19:26:37.177 weirdComparison[15723:20b] bang!
    2009-05-28 19:26:37.178 weirdComparison[15723:20b] ==============
    
    I mean while i - u is negative 'if' operator still fires. But if u is NSInteger or casted to it with (NSInteger), comparison works well. So what are general rules of automatic cast of those types in mixed expressions?
    The problem is that in Cocoa Touch NSUInteger is widely used (indexes, NSString length). While I like to use NSInteger. Even for not negative values when I work with DB: -1 or <0 is for NULL, >= 0 is not negative value itself.
    So extreme caution and 'manual' casting is the only way?
     
  2. HARDWARRIOR thread starter macrumors member

    Joined:
    Nov 17, 2008
    #3
    Thanks!
    First article is really interesting. Actually I found an answer to my question before your post. I mean a common behavior for C to cast int to unsigned int if second operand is unsigned int. But I never knew, that 'value preserving' rule also exists. Though it raises more surprises than solves)
     

Share This Page