Question

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int j = 5;
    while ( ++j < 9)
        cout << j++ << endl;
    cin.get();
    return 0;
}

So I am working on a book, and I understand how these things work, but I am seeking a more concrete explanation of why this prints 6 and 8. Please help me.

Thanks

Was it helpful?

Solution 2

Given:

int j = 5;
while ( ++j < 9)
    cout << j++ << endl;

Why are only 6 and 8 printed?

Upon entering the loop, j is 5. Then the while (++j ... increments that to 6. Then the cout executes, printing out 6. Then the side effect of the j++ takes place, incrementing it to 7.

On the next iteration of the loop, the ++j increments it again, giving 8, which is then printed out. Then the side effect of the j++ takes place, incrementing j to 9.

Then when while (++j < 9) is executed again, j has been incremented to 10, so the while loop exits, and no more is printed.

OTHER TIPS

To understand what it outputs you need to step through the code:

j = 5
j = j + 1 // 6
j < 9 ? yes
output j // 6
j = j + 1 // 7
go to start of loop
j = j + 1 // 8
j < 9 ? yes
output j // 8
j = j + 1 // 9
go to start of loop
j = j + 1 // 10
j < 10 ? no

j starts as 5. It then gets incremented to 6, then compared with 9 in in ++j < 9. This passes the condition, so we go to the next line, where it outputs 6 and then increments j to 7. We go back to the conditional, j is incremented to 8, which is still less than 9, then output, then j is incremented to 9, where the condition fails and the program ends.

++j means the value of j is incremented by 1 and then used in the expression where it appears

j++ means the (current) value of j is used in the expression, after that j is incremented

++j means increase j by one and then evaluate j. j++ on the other hand means evaluate j first and then increase it by 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top