loop condition evaluation

前端 未结 3 650
北海茫月
北海茫月 2020-12-05 04:53

Just a quick question.

I have a loop that looks like this:

for (int i = 0; i < dim * dim; i++)

Is the condition in a for loop re

相关标签:
3条回答
  • 2020-12-05 05:08

    Yes, semantically it will be evaluated on every loop. In some cases, compilers may be able to remove the condition from the loop automatically - but not always. In particular:

    void foo(const struct rect *r) {
      for (int i = 0; i < r->width * r->height; i++) {
        quux();
      }
    }
    

    The compiler will not be able to move the multiplication out in this case, as for all it knows quux() modifies r.

    In general, usually only local variables are eligible for lifting expressions out of a loop (assuming you never take their address!). While under some conditions structure members may be eligible as well, there are so many things that may cause the compiler to assume everything in memory has changed - writing to just about any pointer, or calling virtually any function, for example. So if you're using any non-locals there, it's best to assume the optimization won't occur.

    That said, in general, I'd only recommend proactively moving potentially expensive code out of the condition if it either:

    • Doesn't hurt readability to do so
    • Obviously will take a very long time (eg, network accesses)
    • Or shows up as a hotspot on profiling.
    0 讨论(0)
  • 2020-12-05 05:18

    the compiler will precompute the value of Dim * Dim before the Loop starts

    0 讨论(0)
  • 2020-12-05 05:23

    In general, if you would for example change the value of "dim" inside your loop, it would be re-evaluated every time. But since that is not the case in your example, a decent compiler would optimize your code and you wouldn't see any difference in performance.

    0 讨论(0)
提交回复
热议问题