0

Possible Duplicate:
Difference between declaring variables before or in loop?

Consider the two codes below :

Object i;
for(int i=0;i<10;i++){
    i = new Object();
}

OR

for(int i=0;i<10;i++){
    Object i = new Object();
}

which of the two codes above is better at performance and buffer-overflow.

Community
  • 1
  • 1
armin
  • 1,985
  • 6
  • 38
  • 52
  • I don't understand the question. Both are essentially no-op unless there's some Object's initialization code includes some side-effects. – missingfaktor Feb 03 '12 at 16:35
  • @missingfaktor Presumably `i` would be used somehow. It's just to illustrate the scope of the variable. – Yuck Feb 03 '12 at 16:35

1 Answers1

1

I like to limit variable scope as much as possible. The first option scopes the variable to the entire containing function, while the latter limits it to just within the loop. Therefore, I prefer the latter unless I explicitly need access to the variable after the loop completes.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794