Created
July 31, 2012 18:30
-
-
Save joaoportela/3219297 to your computer and use it in GitHub Desktop.
sample code for comment in http://stackoverflow.com/questions/11738939/never-seen-before-c-for-loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -- original version -- | |
for (u = b.size(), v = b.back(); u--; v = p[v]) | |
b[u] = v; | |
// "unrolled" original version | |
// init | |
u = b.size(), v=b.back(); | |
// condition | |
u--; | |
// code | |
b[u] = v; | |
// increment | |
v = p[v]; | |
// condition | |
u--; | |
// code | |
b[u] = v; | |
// increment | |
v = p[v]; | |
//... until the condition fails |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -- modified version -- | |
for (u = b.size(); (u--) > 0; v = p[v]) | |
{ | |
v = b.back(); // back fetches the last element of vector in c++. | |
b[u] = v; | |
} | |
// "unrolled" modified version | |
// init | |
u = b.size(); | |
// condition | |
(u--) > 0; | |
// code | |
v = b.back(); // <-- on the first iteration it's quite OK, because it really needed to be initialized. | |
b[u] = v; | |
// increment | |
v = p[v]; | |
// condition | |
(u--) > 0; | |
// code | |
v = b.back(); // <-- but here, this statement overwrites whatever value the statement `v=p[v];` put on `v` (not to mention side-effects) | |
b[u] = v; | |
// increment | |
v = p[v]; | |
// ..until condition fails |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment