0

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.

Community
  • 1
  • 1

2 Answers2

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

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

timrau
  • 22,578
  • 4
  • 51
  • 64
2

The first time the loop exit condition (i++) is checked, i's value is 0 (i.e. 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 - i.e. 0.

user93353
  • 13,733
  • 8
  • 60
  • 122