Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with printf as 3rd argument

Tags:

c

for-loop

Studying for a computer science final......

I really cannot figure this example out.....

I understand that leaving the first argument blank makes it act like TRUE....

but I don't understand what leaving a variable in the second argument accomplishes....

What I don't understand the most is how a printf statement "updates" the variable condition...

  #include<stdio.h>
  int main()
  {
    int x=1, y=1;
    for(; y; printf("%d %d\n", x, y))
    {
      y = x++ <= 5;
    }
    printf("\n");
    return 0;
  }

The output is:

2 1
3 1
4 1
5 1
6 1
7 0

edit:

I understand now the for-loop structure part.....

Thanks for the answers - very insightful thanks!

like image 608
snakeopus121 Avatar asked May 08 '13 19:05

snakeopus121


1 Answers

A for loop can be thought of as for (INITIALIZATION; CONDITION; AFTERTHOUGHT)

The first part of the loop is for initialisation. Leaving this empty is fine, it just indicates that you have already initialised any variables required by the loop.

The y in the second expression (or condition) of the for loop is equivalent to y!=0. It keeps the for loop running until y==0.

The printf in the afterthought is run at the end of each iteration but doesn't change the value of y. The loop's body does change y however.

Most textbooks will describe this. Or see Wikipedia or cplusplus.

like image 62
simonc Avatar answered Oct 20 '22 22:10

simonc