Reputation: 51
I was writing a for
loop program when this code came across my mind.
for(int i=1; i<=10; i++,i++)
The program works fine and the output is also correct. But then I tried the following code:
for(int i=1; i<=10; ++i,++i)
for(int i=1; i<=10; ++i,i++)
for(int i=1; i<=10; i++,++i)
To my amazement, all of them produce the same output, 1 3 5 7 9. Now my question is, how exactly do for
loops work and why did all the code produce the same output when I used pre-increment and post-increment in the same for
loop?
Upvotes: 0
Views: 93
Reputation: 19225
Using multiple elements seperated by a comma is only (potentially) problematic if the order of their execution matters.
If you're not using the result of a post/preincrement, and the only thing that matters is the increment itself, then clearly the net result will be the same - adding 2.
Upvotes: 0
Reputation: 35577
i++
means use then increment with a copy and incremented happen later in that line
++i
means increment and use without a copy and increment happen immediately.
That's is the deference here.
Upvotes: 0
Reputation: 81578
it's equivalent to
int i = 1;
while(i <= 10)
{
//stuff would happen here but these loops are all empty
i++;
i++;
}
and
int i = 1;
while(i <= 10)
{
//stuff would happen here but these loops are all empty
++i;
++i;
}
and
int i = 1;
while(i <= 10)
{
//stuff would happen here but these loops are all empty
++i;
i++;
}
and
int i = 1;
while(i <= 10)
{
//stuff would happen here but these loops are all empty
i++;
++i;
}
In which case whether it's pre-increment or post-increment, it doesn't matter at all. It just increments the value of i
by 1
.
Upvotes: 5