Pre-Incrementation VS. Post-Incrementation

Pre increment vs Post increment in array

You hit the nail on the head. Your understanding is correct. The difference between pre and post increment expressions is just like it sounds. Pre-incrementation means the variable is incremented before the expression is set or evaluated. Post-incrementation means the expression is set or evaluated, and then the variable is altered. It's easy to think of it as a two step process.

b = x++;

is really:

b = x;
x++;

and

b = ++x;

is really:

x++;
b = x;

EDIT: The tricky part of the examples you provided (which probably threw you off) is that there's a huge difference between an array index, and its value.

i = ++a[1];

That means increment the value stored at a[1], and then set it to the variable i.

m = a[i++];

This one means set m to the value of a[i], then increment i. The difference between the two is a pretty big distinction and can get confusing at first.

Second EDIT: breakdown of the code

{ 
int a[5] = { 5, 1, 15, 20, 25 } ;
int i, j, k = 1, m ;
i = ++a[1] ;
j = a[1]++ ;
m = a[i++] ;
printf ( "\n%d %d %d", i, j, m ) ;
}

First:

i = ++a[1];

At this point we know a[1] = 1 (remember arrays are zero indexed). But we increment it first. Therefore i = 2.

j = a[1]++;

Remember we incremented a[1] before, so it is currently 2. We set j = 2, and THEN incremented it to 3. So j = 2 and now a[1] = 3.

m = a[i++];

We know i = 2. So we need to set m = a[2], and then increment i. At the end of this expression, m = 15, and i = 3.

In summary,

i = 3, j = 2, m = 15.

Pre-incrementation vs. post-incrementation

Pre- or post-incrementing do not magically delay things until later. It's simply inline shorthand.

Sample Image

// pre-increment
$var = 5;
print(++$var); // increments first, then passes value (now 6) to print()

// post-increment
$var = 5;
print($var++); // passes value (still 5) to print(), then increments

Now let's look at a loop.

for ($i = 0; $i < 9; $i++) {
print($i);
}

The last part of the loop declaration (the $i++) is simply the statement to execute after each time through the loop. It "passes" the value to nowhere, then increments it. $i isn't used anywhere at that time. Later when the next statement is executed (print($i);), the value of $i has already increased.

// add 1, then do nothing with $i
for ($i = 0; $i < 9; ++$i) {}

// do nothing with $i, then add 1
for ($i = 0; $i < 9; $i++) {}

Whichever way you do it, $i will be the same within the loop.


If it helps, you can think of them as small routines that kind of do this:

// ++$i
{
$i = $i + 1;
return $i;
}

// $i++
{
return $i;
$i = $i + 1;
}

As I reread your question, I think the confusion is more with how the loop works than how increment operators work. Keeping in mind that the increment is a straightforward, all-at-once operation, here's how third expression in the loop works.

// here's a basic loop
for ($i = 0; $i < 9; $i++) {
// do loop stuff
print($i);
}

// this is exactly what happens
for ($i = 0; $i < 9; ) {
// do loop stuff
print($i);

$i++;
}

Just because that last line can be put in the loop declaration doesn't give it any special powers. There are no references or anything used behind the scenes. The same $i variable is seen both inside and outside the loop. Every statement inside or outside the loop directly looks up the value of $i when necessary. That's it. No funny business.

Efficiency of postincrement v.s. preincrement in C++

pre-increment introduces a data dependency into your code -- the CPU must wait for the increment operation to be completed before its value can be used in the expression."

Is this true?

It is mostly true - although perhaps overly strict. Pre increment doesn't necessarily introduce a data dependency - but it can.

A trivial example for exposition:

a = b++ * 2;

Here, the increment can be executed in parallel with the multiplication. The operands of both the increment and the multiplication are immediately available and do not depend on the result of either operation.

Another example:

a = ++b * 2;

Here, the multiplication must be executed after the increment, because one of the operands of the multiplication depends on the result of the increment.

Of course, these statements do slightly different things, so the compiler might not always be able to transform the program from one form to the other while keeping the semantics the same - which is why using the post-increment might make a slight difference in performance.

A practical example, using a loop:

for(int i= 0; arr[i++];)
count++;

for(int i=-1; arr[++i];) // more typically: (int i=0; arr[i]; ++i;)
count++;

One might think that the latter is necessarily faster if they reason that "post-increment makes a copy" - which would have been very true in the case of non-fundamental types. However, due to the data dependency (and because int is a fundamental type with no overload function for increment operators), the former can theoretically be more efficient. Whether it actually is depends on the CPU architecture, and the ability of the optimizer.

For what it's worth - in a trivial program, on x86 arch, using g++ compiler with optimization enabled, the above loops had identical assembly output, so they are perfectly equivalent in that case.


Rules of thumb:

If the counter is a fundamental type and the result of increment is not used, then it makes no difference whether you use post/pre-increment.

If the counter is not a fundamental type and the result of the increment is not used and optimizations are disabled, then pre-increment may be more efficient. With optimizations enabled, there is usually no difference.

If the counter is a fundamental type and the result of increment is used, then post-increment can theoretically be marginally more efficient - in some CPU architecture - in some context - using some compiler.

If the counter is not a fundamental type and the result of the increment is used, then pre-increment is typically faster than post-increment. Also, see R Sahu's answer regarding this case.

When to use post increment and pre increment in Java

PRE-increment is used when you want to use the incremented value of the variable in that expression., whereas POST-increment uses the original value before incrementing it.

Whenever your code encounters a PRE-increment, it increments the value of that variable in the memory, then load that value and continues reading the expression.

POST-increment does the opposite, it loads that value of that variable in the memory, then increments the value and continues reading the expression.

To make it more clear, consider this

int i = counter++;

is equivalent to

int i = counter;
counter = counter + 1;

WHEREAS

int i = ++counter;

is equivalent to

counter = counter + 1;
int i = counter;

EDIT: My StackOverflow comments arent working, so I'll just edit it here.

What I'm saying it, it only matters when you use that value in an expression.

sum = 0
counter = 0;
sum = (++counter)+(++counter)+(counter++)

evaluates as

sum = 0
counter = 0
//For first ++counter
counter = counter + 1
sum = counter

//For second ++counter
counter = counter + 1
sum = sum + counter

//For first counter++
sum = sum + counter
counter = counter + 1

Post-increment and pre-increment within a 'for' loop produce same output

After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.

++i increments i and evaluates to the new value of i.

i++ evaluates to the old value of i, and increments i.

The reason this doesn't matter in a for loop is that the flow of control works roughly like this:

  1. test the condition
  2. if it is false, terminate
  3. if it is true, execute the body
  4. execute the incrementation step

Because (1) and (4) are decoupled, either pre- or post-increment can be used.

Post-increment and Pre-increment concept?

All four answers so far are incorrect, in that they assert a specific order of events.

Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.

So.

For the built-in C++ prefix operator,

++x

increments x and produces (as the expression's result) x as an lvalue, while

x++

increments x and produces (as the expression's result) the original value of x.

In particular, for x++ there is no no time ordering implied for the increment and production of original value of x. The compiler is free to emit machine code that produces the original value of x, e.g. it might be present in some register, and that delays the increment until the end of the expression (next sequence point).

Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.

Pre vs Post Increment

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.

post increment vs pre increment - Javascript Optimization

This is what I read and could answer your question: "preincrement (++i) adds one to the value of i, then returns i; in contrast, i++ returns i then adds one to it, which in theory results in the creation of a temporary variable storing the value of i before the increment operation was applied".

Preincrement faster than postincrement in C++ - true? If yes, why is it?

Post-increment usually involves keeping a copy of the previous value around and adds a little extra code. Pre-increment simply does it's job and gets out of the way. I typically pre-increment unless the semantics would change and post-increment is actually necessary.



Related Topics



Leave a reply



Submit