Objective C, difference between n++ and ++n
In Objective-C, i开发者_如何学JAVAs there any difference between n++ and ++n (eg. used in a for loop)?
++n;
increments the value of n
before the expression is evaluated.
n++;
increments the value of n
after the expression is evaluated.
So compare the results of this
int n = 41;
int o = ++n; //n = 42, o = 42
with the results of this:
int n = 41;
int o = n++; //n = 42, o = 41
In the case of loops:
for (int i = 0; i < j; i++) {/*...*/}
however it doesn't make any difference, unless you had something like this:
for (int i = 0; i < j; x = i++) {/*...*/}
or this:
for (int i = 0; i < j; x = ++i) {/*...*/}
One could say:
It doesn't matter whether to use
n++
or++n
as long as no second (related) variable is modified (based on n) within the same expression.
The same rules apply to --n;
and n--;
, obviously.
++n increments the value before it's used (pre-increment) and n++ increments after (post-increment).
In the context of a for loop, there is no observable difference, as the increment is applied after the code in the loop has been executed.
++n
and n++
differ in what the expression evaluates to. An example:
int n = 0;
NSLog(@"%d", n); // 0
NSLog(@"%d", n++); // still 0, increments afterwards
NSLog(@"%d", n); // 1
NSLog(@"%d", ++n); // 2, because it increments first
NSLog(@"%d", n); // 2
In a loop it wont make a difference. Some people say ++n
is faster though
In Scott Meyers "More Effective C++" Book he makes a very rational case for preferring prefix increment to postfix increment. In a nutshell, in that language due to operator overloading facilities prefix increment is almost always faster. Objective C doesn't support overloaded operators but if you have or ever will do any C++ or Objective-C++ programming then preferring prefix increment is a good habit to get into.
Remember that most of the time ++n looks like:
n = n + 1 [do something with n]
Whereas n++ looks like (if used as intended):
register A = n; // copy n [do something with n] n = A + 1;
As you can see the postfix case has more instructions. In simple for loops most compilers are smart enough to avoid the copy if it's obvious that the pre-increment n isn't going to be used but that case devolves to the prefix case.
I Hope this makes sense. In summary you should use prefix unless you really want the "side-effect" behavior of evaluate then increment that you get from the postfix version.
As stated above,
--n decrements the value of n before the expression is evaluated.
n--; decrements the value of n after the expression is evaluated.
The thing here to note is when using while loops
For example:
n = 5
while(n--) #Runs the loop 5 times
while(--n) #Runs the loop 4 times
As in n-- the loop runs extra time while n = 1 But in --n 1 is first decremented to 0, and then evaluated. This causes the while loop to break.
精彩评论