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?

Recommended Answers

All 5 Replies

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

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.

thanks both of you :)

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.

sure deceptikon thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.