简体   繁体   中英

Variable Declaration Inside For Loop Initialization Statement

I have a simple question with regards to initializing for loops.

Here is my for loop declaration:

for (int i=player.x-xIndex-1; i<=player.x+xIndex+1; i++)
{
    for (int j=player.y-yIndex-1; j<=player.y+yIndex+1; j++)
    {

    }
}

My question is:

Is it bad practice to have the values of the indices i and j be set to non-static integer values at declaration?

Will the code just evaluate the minimum and maximum values of i and j once at beginning of execution, or will it evaluate those values (ie player.x+xIndex+1, etc.) every single time the loop executes.

Any light you guys can shed on my problem would be awesome!

I'm a freakin' amateur, guys. Seriously.

Thanks :D

Not an amateur question at all. The "initialization" expressions are calculated only on the first run through, because of course they're only used that one time.

For the loop's "condition" (the middle expression that is tested at the end of every iteration), in the worst case it can be evaluated every iteration. Because what if (in this case) player.y actually changes during the loop?

However, most modern compilers will likely not compute that whole thing every loop if they can detect that the end value is provably never changing during the loop.

If you wanted to be double sure and manhandle the path of execution, you can explicitly "hoist" the conditional end expression out of the loop yourself, like:

int maxValue = foo.x + y.bar + 12 + myString.length;
for (int i = 0; i < maxValue; i++) {
    ....

But now the standard style disclaimer: optimizing prematurely can make your code less readable for no provable gains. Unless you're doing real work in that condition expression, or the loop is running bazillions of iterations, some additional computation won't hurt you much, and might be worth keeping so that it's clearer to yourself and others what you're trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM