Am I allowed to re-use the same variable name in different for loops in Objective-C? For example:
// This doesn't give me an error but I feel like it should:
for(int i = 0; i < 10; i++){
//do something
}
for (int i = 0; i < 5; i++){ // I'm using "i" again. Is this allowed?
//do something else
}
This compiles and seems to run fine, but I just want to make sure that this is legal and allowed without causing some sort of complication in my program. I’m newish to ObjC, but in Java I normally would get errors from this.
That should be fine. The scope of
iin the snippet you show is limited to each of theforloops, so there’s no conflict. If you instead do it like this:then you’ll have a problem because you’re declaring
itwice in the same scope.