Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSInteger = NSInteger -1?

Tags:

objective-c

I am trying to do a very simple thing but I can't figure out how;

NSInteger * a=10;
a=a-1;
NSlog(@"a=%d",a);

For some reason it's showing a=6.

How can it be?

like image 783
Reimond Hill Avatar asked Nov 22 '25 15:11

Reimond Hill


1 Answers

Your problem is that you've declared the variable a as a pointer. Most Objective-C variables are pointers, but NSInteger is an exception, because it's just typedef'd to int or long.

Your code should look like this:

NSInteger a=10;
a=a-1;
NSlog(@"a=%d",a);

When you do math on a pointer, you are actually moving the location in memory it points to. For example if the size of an NSInteger is 4 (sizeof(NSInteger) == 4), moving it -1, or in other words, a one structure size back, the pointer gets decreased by 4. This mechanique is heavily used in C when iterating arrays of structures, e.g.

CGPoint myPoints[4];
CGPoint* point = myPoints; //get the first point

for (NSUInteger i = 0; i < 4; i++) {
   CGPoint currentPoint = *point;
   point++; //moves to the next point, adding sizeof(CGPoint)
}

This is called pointer arithmetic and you can write it in different ways, e.g. pointer + 1 but also point[1] or 1[point] (the last two are actually equal to *(pointer + 1)).

like image 146
Alyssa Ross Avatar answered Nov 24 '25 06:11

Alyssa Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!