简体   繁体   中英

simple c++ loop prefix postfix operator

#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

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.

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.

++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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM