简体   繁体   中英

Using cout inside an FOR loop

I tried testing the following code and found that the loop is never executed :

   int i=0; 
   for(;i++;cout<<i)
   {
          if(i==5) 
                 break; 
   }

I read the following post about the value returned by cout from the following post :

What's the difference between cout<<cout and cout<<&cout in c++?

But, I am unable to figure out why. Can someone help me with this.

int i = 0;
for (; i++; cout << i)

At the 1st loop, i++ is evaluated as 0 before increment happens and thus terminates the loop.

The first time the loop exit condition ( i++ ) is checked, i 's value is 0 (ie false). Hence it never enters the loop.

i++ is post increment. So i becomes 1 but the value which is checked in the loop exit condition is the value before increment - ie 0.

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