Increment in C ++ - When to use x ++ or ++ x?

I am currently learning C ++, and some time ago I found out about incrementality. I know that you can use "++ x" to do the increment earlier and "x ++" do it after.

However, I really don't know when to use either of the two ... I never used "++ x", and things have always worked fine so far - so when should I use it?

Example: In a for loop, when is it preferable to use "++ x"?

Also, can someone explain how different increments (or decrements) work? I would be very grateful.

+52
c ++ post-increment pre-increment
Nov 28 '09 at 16:45
source share
10 answers

This is not a matter of preference, but logic.

x++ increments the value of x after processing the current statement.

++x increments the value of x before processing the current statement.

So just solve the logic you write.

x += ++i will increase i and add i + 1 to x. x += i++ will add i to x and then increase i.

+70
Nov 28 '09 at 16:47
source share

Scott Myers tells you to prefer a prefix, unless the logic determines that postfix is ​​appropriate.

"More Effective C ++" item # 6 is enough credibility for me.

For those who do not own the book, here are the relevant quotes. On page 32:

From your day on as a C programmer, you may recall that the prefix form of the increment operator is sometimes called “increment and select”, and the postfix form is often known as “select and increment”. Two phrases are important for memorization because they all act as formal specifications ...

And on page 34:

If you are the one who is worried about efficiency, you probably fell into a sweat when you first saw the postfix increment function. This function should create a temporary object for the return value, and the implementation above also creates an explicit temporary object that must be constructed and destroyed. The prefix increment function does not have such temporary ...

+36
Nov 28 '09 at 16:49
source share

From cppreference when increasing iterators:

You should prefer operator (++ iter) pre-increment for operator (iter ++) post-increment if you are not going to use the old value. The post-increment is usually done as follows:

  Iter operator++(int) { Iter tmp(*this); // store the old value in a temporary object ++*this; // call pre-increment return tmp; // return the old value } 

Obviously, it is less efficient than pre-incrementing.

A preliminary increment does not create a temporary object. This can be significant if your facility is expensive to build.

+14
Nov 28 '09 at 16:57
source share

I just want to notice that the generated code is the same if you use pre / post incrementation, where semantics (pre / post) doesn't matter.

Example:

pre.cpp:

 #include <iostream> int main() { int i = 13; i++; for (; i < 42; i++) { std::cout << i << std::endl; } } 

post.cpp:

 #include <iostream> int main() { int i = 13; ++i; for (; i < 42; ++i) { std::cout << i << std::endl; } } 

_

 $> g++ -S pre.cpp $> g++ -S post.cpp $> diff pre.s post.s 1c1 < .file "pre.cpp" --- > .file "post.cpp" 
+5
Nov 28 '09 at 17:19
source share

The most important thing to remember, imo, is that x ++ must return the value before the actual increment has occurred - therefore, it must make a temporary copy of the object (pre increment). This is less efficient than ++ x, which grows in place and returns.

Another thing worth mentioning is that most compilers will be able to optimize such unnecessary things when possible, for example, both options will lead to the same code:

 for (int i(0);i<10;++i) for (int i(0);i<10;i++) 
+4
Nov 28 '09 at 22:56
source share

I agree with @BeowulfOF, although for clarity, I have always advocated separating statements so that the logic is absolutely clear, i.e.:

 i++; x += i; 

or

 x += i; i++; 

So, I answer that if you write clean code, then that rarely matters (and if that matters, then your code is probably not clear enough).

+2
Nov 28 '09 at 16:57
source share

You correctly explained the difference. It just depends on whether you want to increase x before each run through the loop or after. It depends on your program logic, which is appropriate.

An important difference when working with STL Iterators (which also implement these operators) is that it ++ creates a copy of the object that the iterator points to, then increases and then returns a copy. ++, on the other hand, does the increment first, and then returns a reference to the object that the iterator now points to. This is mostly true when every performance bit is counted or when you implement your own STL iterator.

Edit: fixed mix of prefix and suffix notation

+1
Nov 28 '09 at 16:51
source share

I just would like to emphasize that ++ x is expected to be faster than x ++ (especially if x is an object of some arbitrary type), therefore, if this is not required for logical reasons, ++ x should be used.

+1
Nov 28 '09 at 16:57
source share

Understanding the syntax of a language is important when considering code clarity. Consider copying a character string, for example, followed by an increment:

 char a[256] = "Hello world!"; char b[256]; int i = 0; do { b[i] = a[i]; } while (a[i++]); 

We want the loop to execute when it encounters a null character (which checks false) at the end of the line. This requires testing the value of the pre-increment, as well as increasing the index. But not necessarily in that order - the way to encode this with a preliminary increment would be:

 int i = -1; do { ++i; b[i] = a[i]; } while (a[i]); 

This is a matter of taste, which is clearer, and if a machine has several registries, both should have the same runtime, even if the function [i] is expensive or has side effects. A significant difference may be the value of the index output.

0
Nov 02 '14 at 16:34
source share

Postfix form of ++ operator - follows the use-then-change rule,

The prefix form (++ x, - x) follows the change-then-use rule.

Example 1:

When several values ​​are cascaded with <using cout, then the calculations (if any) are performed from right to left, but printing is done from left to right, for example, (if val, if initially 10)

  cout<< ++val<<" "<< val++<<" "<< val; 

will result in

 12 10 10 

Example 2:

In Turbo C ++, if several occurrences of ++ or (in any form) are found in the expression, then all prefix forms are calculated first, then the expression is calculated and, finally, the final forms are written, for example,

 int a=10,b; b=a++ + ++a + ++a + a; cout<<b<<a<<endl; 

It will be output in Turbo C ++ will

 48 13 

While it is output in a modern compiler, there will be (because they strictly follow the rules)

 45 13 
  • Note. Multiple use of increment / decrement operators on one variable in one expression is not recommended. The processing / results of such expressions vary from compiler to compiler.
0
Nov 07 '15 at 7:27
source share



All Articles