Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pre-increment and post-increment in a loop?

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?

like image 381
GurdeepS Avatar asked Jan 27 '09 17:01

GurdeepS


People also ask

What is difference between i ++ & ++ 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.

Is ++ and ++ i in for loop the same?

Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated. To answer the actual question, however, they're essentially identical within the context of typical for loop usage.

Which is faster Preincrement and Postincrement?

As a result, pre-increment is faster than post-increment because post-increment keeps a copy of the previous value where pre-increment directly adds 1 without copying the previous value.

Does pre increment matter in for loop?

As we said before, the pre-increment and post-increment operators don't affect the semantics and correctness of our loop when we use them to increase its counter.


1 Answers

a++ is known as postfix.

add 1 to a, returns the old value.

++a is known as prefix.

add 1 to a, returns the new value.

C#:

string[] items = {"a","b","c","d"}; int i = 0; foreach (string item in items) {     Console.WriteLine(++i); } Console.WriteLine("");  i = 0; foreach (string item in items) {     Console.WriteLine(i++); } 

Output:

1 2 3 4  0 1 2 3 

foreach and while loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:

for (int i = 0; i < 5; i++) { Console.Write(i);} Console.WriteLine(""); for (int i = 0; i < 5; ++i) { Console.Write(i); } 

0 1 2 3 4
0 1 2 3 4

If the value as evaluated is used then the type of increment becomes significant:

int n = 0; for (int i = 0; n < 5; n = i++) { } 
like image 141
Chris S Avatar answered Sep 24 '22 09:09

Chris S