I was not really clear with the post increment operator that I always used with for loops. My latest and newly acquired understanding of post increment operator is the following:
int a = 5
int b = a++ //a will increment and return back its old value 5
so b = 5
Armed with this new knowledge i decided to understand/apply it to the places where i commonly used the post increment operator as in a for
loop . Now it seems like I am lost
since I am ending up with the wrong output theoretically
Consider the following code
for(int i=0 ; i< 3 ; i++)
{
std::cout << i;
}
First loop
i starts with 0 which is less than 3 so ( increment by 1 however since its i++ it returns old value 0)
so cout should display 1 // But it displays 0
Second Loop
i is now 1 which is less than 3 so i++ is applied - Now i is 2 and returns back 1
so cout should display 2 //But it display 1
Third Loop
i is now 2 which is less than 3 so i++ is applied - Now i is 3 and returns back 2
so cout should display 3 //But it display 2
Fourth Loop
i is now 3 which is not less than 3 so loop exits
Could anyone please clear my understanding and point me in the right direction. The output should be 0,1,2 where am i going wrong ?
It makes no difference in a for loop. The difference between ++i and i++ is when you are trying to use the value of i in the same expression you are incrementing it.
In Post-Increment, the operator sign (++) comes after the variable. It assigns the value of a variable to another variable and then increments its value. Preincrement and Postincrement in C are very useful and handy operators, especially when it is used inside the loops.
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. operators in our classes. Using such an object as our loop's counter, we may see that the post-increment alternative runs slower than the pre-increment one.
What you're missing is when each of those sections of the for
statement happen:
for (int i = 0 ; i < 3 ; i++)
// 111111111 22222 333
Now re-read that last bullet point carefully. The i++
is done at the end of an iteration, after the cout << i
. And, immediately after that, the continuation condition is checked (the second part).
So the loop is effectively the same as:
{ // Outer braces just to limit scope of i, same as for loop.
int i = 0;
while (i < 3) {
cout << i;
i++;
}
}
That's why you get 0 1 2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With