Diego Favero
Diego Favero

Reputation: 2115

Why does the ++ operator increase an integer by 4 and not by 1?

I've got some simple code in Objective-C wich consist of a button and a label. When you click the button once, the labels shows: "u hit me", if you click it twice, the message will be: "i did it again". But, if u hit the button 5x or more, the message should be: "STOP THAT";

I used simple ifs and a counter that is increased using the operator ++. The problem is: My counter increases in steps of 4, and not in steps of one.

Here's the code

@implementation hitMe

NSString *myString = @"";
int *counter = 0;

- (IBAction)htM:(id)sender {
    if ([myString isEqualToString:@""]){
        //first hit
        myString = @"u hit me";
    } else {  
    //  second and next hits...
        myString = @"u did it again!";
        counter++;
    }

    // if I use "counter > 5" it doesn't work,
    // I have to use 21 if I want the button hit 5 times before
    // I get the "STOP THAT" message

    if (counter > 21) {
        myString = @"STOP THAT ";
    } 

    [labelOne setStringValue:myString];

    // I used this only to check the count value
    [labelTwo setIntValue:counter];
}

@end

Upvotes: 3

Views: 3724

Answers (1)

Seamus Campbell
Seamus Campbell

Reputation: 17906

The variable you're incrementing, counter, is a pointer to an int, not an int. So the compiler turns:

counter++;

into

counter += 4; // sizeof(int) == 4

which is what is needed to get to the next word in memory, or the next location you might point to. This might seem weird, but if you had an array of ints and a pointer that you were using to examine them, incrementing the pointer would take you to the next int (which is four bytes on most architectures these days).

Change int *counter to int counter and you should be fine.


Edit: The C language spec defines pointer arithmetic (what happens when you add or subtract with pointers) this way because the most common use of pointer math is to navigate around an array that you're pointing to. So one unit of increment for a pointer is one unit of the array, or sizeof(arrayType). A char* would have given you the behavior you expected, because sizeof(char) is 1.

Upvotes: 21

Related Questions