Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre vs Post Increment

Tags:

c++

c++14

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

like image 332
Tman Avatar asked May 17 '19 05:05

Tman


People also ask

What is pre increment and post increment with example?

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.

What is the difference between ++ i and ++ i?

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.

What is the difference between ++ before and after?

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.

What is difference between ++ A and A ++ in C?

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.


1 Answers

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:

  1. Computation of counter is sequenced, which could be part of the entire RHS of the statement or just the term counter++.
  2. Computation of counter += 1 is sequenced before the next statement in the program is sequenced.

There are two things to keep in mind.

  1. The value of a term -- what it evaluates to in an expression.
  2. The side effects of the evaluation of the term.

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.

like image 142
R Sahu Avatar answered Oct 09 '22 09:10

R Sahu