开发者

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

开发者 https://www.devze.com 2023-02-21 19:25 出处:网络
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 a

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 = @"STO开发者_高级运维P THAT ";
    } 

    [labelOne setStringValue:myString];

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

@end


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号