I get the basis for the pre and post increment, but having trouble wrapping my mind when it actually takes place on a post increment.
For example in the following post increment code:
int counter = 10;
int result = 0;
result = counter++ + 10;
cout << "Counter: " << counter << endl;
cout << "Result: " << result << endl;
I understand that Counter will come out as 11 and result at 20. Is Result coming out at 20 because the entire function is being run, and THEN it is adding +1 when the program goes to return 0; ?
When exactly is that +1 getting added?
Thanks
Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented. The following is the syntax of pre and post increment. ++variable_name; // Pre-increment variable_name++; // Post-increment.
The only difference is the order of operations between the increment of the variable and the value the operator returns. So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.
Description. If used postfix, with operator after operand (for example, x++ ), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x ), the increment operator increments and returns the value after incrementing.
More precisely, the post-increment a++ and the pre-increment ++a have different precedence. As you can see, a++ returns the value of a before incrementing. And ++a returns the value of a after it has been incremented.
When exactly is that +1 getting added?
According to the standard:
The value computation of the ++ expression is sequenced before the modification of the operand object.
From a layman's point of view:
counter
is sequenced, which could be part of the entire RHS of the statement or just the term counter++
.counter += 1
is sequenced before the next statement in the program is sequenced.There are two things to keep in mind.
In the case of counter++
:
The value of the term is the value of counter
before it is incremented.
The side effect of evaluation of the term is incrementing of the value of counter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With