Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int++ increments by 4

Here's my code:

- (IBAction)NextTouched:(id)sender {
    NSLog(@"Index = %i", index);
    if([project getCount]>(index++)) {
        [self setUI:index];
    }
}

Index is an integer, as declared in my .h file:

@property (nonatomic) int *index;

But every time I click the button, the log says the integer is going up by 4. Can you tell my why?

like image 461
Todd Davies Avatar asked Jun 08 '26 10:06

Todd Davies


1 Answers

The reason it's going up by 4 is because index is a pointer. When you increment a pointer its value increases by the size of the data type it points to, in this case an int, which is 4 bytes.

Given index appears to be an index into an NSArray (or some other collection class), I think you want to make it int and not int * to solve your issue. Better still make it unsigned, like NSUInteger, which is the type returned from the count method.

Also I think you'll want to use prefix-increment rather than postfix-increment so that the if test uses the newly incremented value, not the previous value.

like image 176
trojanfoe Avatar answered Jun 11 '26 02:06

trojanfoe