For loop question

I used a simple for loop in a program ie (int i =0 ; i<x ; i++) , but now i need to use the value of i avter the incrementation for another equation and i get the "i hasn t been declared in this scope" error. why does this happen ? doesn't the previous declaration count ? thanks
The
1
2
3
4
for (int i =0 ; i<x ; i++)
{
  // body
}


is like
1
2
3
4
5
6
7
{
  int i =0;
  for ( ; i<x ; i++)
  {
    // body
  }
} // the i is no more 

The loop is a scope of its own. The variables declared in the loop exists only within the loop.

1
2
3
4
5
6
int i =0;
for ( ; i<x ; i++)
{
  // body
}
// use i 


Note: if the loop body does not change i nor have a break, then you do know that i is the smallest int, where i<x is false.
Last edited on
closed account (1vf9z8AR)
Telling the above in simple terms declare int i outside for loop and use only i in for loop;
example
1
2
3
4
5
6
7
8
9
int main()
{
int i;
for(i=0;i<x;i++)
{
//body of for loop
}
return 0;
}

Topic archived. No new replies allowed.