Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C, why does this increment by 4 instead of 1?

In Objective-C, I have a simple block of code that increments a counter each time a button is pushed. My logs, and even updates to the interface, are showing an increment of 4 instead of one. Is this just a display issue with my formatting (I'm using %d) or something else I'm missing? My guess lies with the "%d" but I'm new to Objective-C and not sure. (Note, I also tried "counter += 1;" with the same result.

int counterValue = 0;
NSLog(@"Count at init: %d",counterValue);
...

-(IBAction)pushButton { 
    NSLog(@"Count (Pre-Push) = %d",counterValue);
    counterValue++;
    NSLog(@"Count (Post-Push) = %d",counterValue);
}

The output is as follows:

2010-02-20 18:39:39.125 My App[37536:207] Count at init:  0
2010-02-20 18:39:39.845 My App[37536:207] Count (Pre-Push) = 0
2010-02-20 18:39:39.846 My App[37536:207] Count (Post-Push) = 4
2010-02-20 18:39:40.165 My App[37536:207] Count (Pre-Push) = 4
2010-02-20 18:39:40.166 My App[37536:207] Count (Post-Push) = 8
2010-02-20 18:39:40.727 My App[37536:207] Count (Pre-Push) = 8
2010-02-20 18:39:40.728 My App[37536:207] Count (Post-Push) = 12
like image 778
jbnunn Avatar asked Feb 23 '10 00:02

jbnunn


1 Answers

The code you're showing sure shouldn't do that. I made quick program to doublecheck, and I get the expected results:

2010-02-22 17:04:35.787 app[68267:a0f] Count (Pre-Push) = 0
2010-02-22 17:04:35.790 app[68267:a0f] Count (Post-Push) = 1
2010-02-22 17:04:35.923 app[68267:a0f] Count (Pre-Push) = 1
2010-02-22 17:04:35.924 app[68267:a0f] Count (Post-Push) = 2

My best guess is that you have shadowed counterValue with another variable of type int *, which is making the + increment by sizeof(int) instead of by 1.

like image 102
Carl Norum Avatar answered Sep 20 '22 06:09

Carl Norum