Detail the sequence of execution of the expression and body of the loop in the for loop

  • 2020-06-07 04:53:15
  • OfStack

For those of you who are c students, the for loop may be one of the most frequently used loop statements

for(expression 1; Expression 2; Expression 3) {loop body}

Knowing the order in which the statements are executed can save us a lot of mistakes

We can use the following small program to easily measure the internal statement loop sequence:


#include<stdio.h>
void main()
{
int i;
for (printf("#1\n"),i=1;
  printf("#2\n"),i<=5;
  printf("#3\n"),i++)
{
    printf("hello\n") ; 
}
}

It is not hard to see from the above execution results that in for loop except for expression 1, in order to initialize variables, its loop is the loop of expression 2 -- loop body -- expression 3 -- expression 2.


Related articles: