0

I have a little confusion in my mind. I know very well the difference between preincrement and postincrement, postdecrement and predecrement.
But i wonder how do these operators work during loop.
I ,myself, use postincrement or decrement in loop as follows:

for(int i=0;i<5;i++)
{
 //code
} 

But in my book I read mostly preincrement as:

for(int i=0;i<5;++i)
{
 //code;
} 

So ,in short, my point is ...What is the difference between these two loops?

Edited by Mahnoor_1

4
Contributors
5
Replies
27
Views
1 Year
Discussion Span
Last Post by Mahnoor_1
Featured Replies
  • 1

    > I think this is an old micro-optimisation thing that is irrelevant with modern compilers. It was irrelevant even in prehistoric times too, unless you were working with one of the dumbest compilers ever. Even Dennis Ritchie's first C compiler performed this optimization. However, note that the type of `i` … Read More

0

There's only a difference when you use the return value of the increment for something. So the two loops are completely equivalent.

0

I think this is an old micro-optimisation thing that is irrelevant with modern compilers. The preincrement just adds 1 but the postincrement theoretically requires you to store the initial value before incrementing. Nowdays that would be optimised out anyway.

1

I think this is an old micro-optimisation thing that is irrelevant with modern compilers.

It was irrelevant even in prehistoric times too, unless you were working with one of the dumbest compilers ever. Even Dennis Ritchie's first C compiler performed this optimization.

However, note that the type of i matters. For int (or any built-in type, generally), the two are functionally identical. For class types that overload the ++ operator, the prefix version will likely be slightly more efficient.

This question has already been answered. Start a new discussion instead.
Be sure to adhere to our posting rules.