KcFnMi KcFnMi - 1 month ago 13
C++ Question

Why for(int i=0; i<10; ++i) and for(int i=0; i<10; i++) returns the same?

Why

for(int i=0; i<10; i++)
std::cout << i << std::endl;


and

for(int i=0; i<10; ++i)
std::cout << i << std::endl;


returns the same:

0 1 2 3 4 5 6 7 8 9


I was expecting the pre-increment to return:

1 2 3 4 5 6 7 8 9 10


Since it increments it self before return, right?

Answer

A for loop like

for(int i=0; i<10; i++)
    std::cout << i << std::endl;

is basically the same as the following:

{
    int i = 0;  // For loop initializer
    while (i < 10)  // For loop condition (and the actual loop)
    {
        std::cout << i << std::endl;  // For loop body
        i++;  // For loop post-expression
    }
}

Now changing the loop "post-expression" i++ to ++i will not make any difference, since its result is really thrown away, and it's performed at the end of the loop.