for loop go in infinite loop why

#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int i;
for(i=0;i<10;i=i++)
{
cout<<"\t"<<i;
getch();
}
getch();
}
why loop goes infinite
pls explain
i=i++ This modifies the variable i twice with no sequence point in between. That is not allowed so your program will have undefined behaviour which means that anything could happen.

You probably meant to write i++ or i=i+1.
can u pls elaborate it i m not clear with ur answer
1
2
3
4
5
for(i=0;i<10;i++)
{
cout<<"\t"<<i;
getch();
}
dear my question is wt is actually compiler do for this particular statement in
c++
for(i=0;i<10;i=i++)
It's undefined, thus the result depends on the implementation of your compiler.
i++, or post-increment, increments the variable but returns the old value (before incrementing).

An example:
1
2
int i = 5, j = 10;
j = i++;

j will now be 5 (equal to old value of i), while i becomes 6.

It should now be obvious why i = i++; can only lead to problems.

dear my question is wt is actually compiler do for this particular statement in
c++
for(i=0;i<10;i=i++)
what it does is that first it increases i then sets i to the old value. Which effectively means that i remains 0

Very odd, this works fine in gcc 4.6.2

1
2
    for(i=0;i<10;i=i++)
        cout << i;



0123456789

i think you don't understand "undefined." The term doesn't mean that the output will always be erroneous. There is simply no guarantee of what will happen. Consider delete [] p; How does the compiler know how much to delete; you never specified. Well there's a particular implementation that stores the total number of elements/space/size taken by vector p in address just before the start of &p[0]. Now you can use this information and send p to a function without specifying it's size as another parameter and get away with it. This however doesn't mean you are doing it right. Undefined can be implementation specific too.
Very odd, this works fine in gcc 4.6.2
it's not that odd. It's an optimization that can be done for primitive data types only (first set old value then increase).

That also means that the behaviour of such a statement may differ in the debug an the release version
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int i;
for(i=0;i<10;i++)
{
cout<<"\t"<<i;
}
getch();
}
//you r missing symbol { that's by your program always show zero ... plz see my programm
Topic archived. No new replies allowed.