-2

I want to know what the difference is between defining an iteration variable before (outside) the for statement that uses it, as below...

    int i;
    for(i=1;...)

...Against defining the variable within the for statement, as below:

    for(int i=1;...)
Tagc
  • 8,736
  • 7
  • 61
  • 114

5 Answers5

1

The answer to this question is actually very simple. int i; for (i = 1; ) and for (int i = 1; ). The difference between the two is that one declares i outside of the for loop while the other declares i on the inside. Either way is completely fine and will result in the same amount of loops in the program. I hope this helps.

Edit: I should also mention that if you declare i inside of the for loop, it will not be accessible outside of the for loop.

zarak
  • 2,933
  • 3
  • 23
  • 29
0

They have different scope

pre-declaration, you can access i outside the for loop

int i;
for(i=1;...)
 {
    // i accessible here
 }
 // i accessible here
i = 10; // will work and update i outside for loop

inline declaration, this case you only can access the i inside the for loop

 for(int i=1;...)
  {
     // i accessible here
  }
   // but not accessible here
 i = 10; // won't work outside for loop
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
  • There has got to be some difference my teacher told me there's a difference are you sure there is no difference at all between these two except the pre-declaration and inline declaration? – user3607864 Aug 07 '16 at 17:08
  • @user3607864 see my update hope will help – Mostafiz Aug 07 '16 at 17:21
0

Likely the most significant difference is scope: in the first example. local variables like your i are visible inside the block they are defined. So in your first example, i will continue to exist (and have its then current value) after the for loop, while in the second case, it will be valid only in the for loop and loop body.

Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
0

The diffence is in the variable scope. When you declare a variable outside of the for-loop (like in your first example) it will be accessible in the loop and outside of the loop.

int i;
for(i=1; i<100; i++)
{ 
    // do great things
}

i = 10000; // Works fine

When you declare it in the loop declaration, it won't be accessible outside of the loop.

for(int i=1; i<100; i++)
{ 
    // do great things
}

i = 10000; // Won't compile
Ar4i
  • 31
  • 3
0

The difference lies within the scope of variable i. In first case let's say your code is:

void SomeFunction(){
    int i;
    for(..){
        .. 
        // i is available here
    }
    // And here too
}

While in second case it's only available inside the loop block{}. Outside, it'll give error.

 void SomeFunction(){
    for(int i;..){
        .. 
        // i is available here
    }
    // But not here
}
Mridul Kashyap
  • 704
  • 1
  • 5
  • 12