loop variable inside the loop question

Hello everyone,

1
2
for(int i = 0) {
    for( int j = 0 ) { } }


1
2
3
int i, j;
for(i = 0) {
    for( j = 0 ) { } }


1. Should I be worried about declaring a variable inside the loop like this or would the compiler 'optimize' it for me anyways?
( running c++ compiles with default settings )

2. What about other variables declared inside the loop?
Thanks!

I think you should not be worried.

if you are using for loop then is best to do like this:

for (int i = 0; i < TimesToLoop; i++){

}

Also dont declare variables inside loop like this:

while(){
int i=0; NOT GOOD!
}
Last edited on
you can declare the variable inside for loop that is good habit
Basic types can be allocated on the stack in zero time, so these two snippets have identical performance:
1
2
3
4
5
int i;
/*some loop*/{
    i = 0;
    // etc.
}
1
2
3
4
/*some loop*/{
    int i = 0;
    // etc.
}
Likewise for these:
1
2
3
4
5
for (int i = 0; i < n; i++){
    for (int j = 0; j < m; j++){
        // etc.
    }
}
1
2
3
4
5
6
int i, j;
for (i = 0; i < n; i++){
    for (j = 0; j < m; j++){
        // etc.
    }
}

In the general case, the same does not hold true for objects. A class may define arbitrarily complex constructors. For example, a constructor might open a TCP connection and get some info from a web server, which may take an unknown amount of time. You need to decide on a case-by-case basis when and where to allocate an object, taking into account the things its constructor and destructor do.
Last edited on
Topic archived. No new replies allowed.