foreword
I encountered it when I was brushing the questions today, so I will briefly record it (maybe I don’t know). In C language, both i++ and ++i mean self-increment. The difference is that ++i is first increased and then assigned, while i++ is first assigned and then increased. I think there are beginners like me who have always had doubts before: they are both similar, so when to use i++ and when to use ++i? Today I learned that the judgment mechanism of i++ and ++i in the loop is different.
for loop
In the for loop, i++ and ++i are the same, they are judged first and then added.
for (int i = 0; i < 5; i++)
{
cout << i << " ";
}
for (int i = 0; i < 5; ++i)
{
cout << i << " ";
}
The output is the same.
while loop
In the while loop, i++ and ++i are different: i++ first judges and then increases before entering the loop body:
int i = -5;
while (i++ < 0)
{
cout << i << " ";
}
In the above code, first judge that i == -5 is less than zero, then increment i = i + 1, and finally enter the loop;
And ++i is to increase first and then judge and then enter the loop body:
i = -5;
while (++i < 0)
{
cout << i << " ";
}
In the above code, first increment i = i + 1, then judge that i == -4 is less than zero, and finally enter the loop;
The test results are as follows:
do-while loop
The i++ and ++i in the do-while loop are the same as in the while loop, except that the do-while executes the loop body first:
cout << "do-while循环i++:";
i = -5;
do
{
cout << i << " ";
} while (i++ < 0);
cout << "do-while循环++i:";
i = -5;
do
{
cout << i << " ";
} while (++i < 0);