Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Loop-invariant code motion
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Example== In the following code sample, two optimizations can be applied. <syntaxhighlight lang="C"> int i = 0; while (i < n) { x = y + z; a[i] = 6 * i + x * x; ++i; } </syntaxhighlight> Although the calculation <code>x = y + z</code> and <code>x * x</code> is loop-invariant, precautions must be taken before moving the code outside the loop. It is possible that the loop condition is <code>false</code> (for example, if <code>n</code> holds a negative value), and in such case, the loop body should not be executed at all. One way of guaranteeing correct behaviour is using a conditional branch outside of the loop. Evaluating the loop condition can have [[Side effect (computer science)|side effects]], so an additional evaluation by the <code>if</code> construct should be compensated by replacing the <code>while</code> loop with a <code>[[Do while loop|do {} while]]</code>. If the code used <code>do {} while</code> in the first place, the whole guarding process is not needed, as the loop body is guaranteed to execute at least once. <syntaxhighlight lang="C"> int i = 0; if (i < n) { x = y + z; int const t1 = x * x; do { a[i] = 6 * i + t1; ++i; } while (i < n); } </syntaxhighlight> This code can be optimized further. For example, [[strength reduction]] could remove the two multiplications inside the loop (<code>6*i</code> and <code>a[i]</code>), and [[induction variable]] elimination could then elide <code>i</code> completely. Since <code>6 * i</code> must be in lock step with <code>i</code> itself, there is no need to have both.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)