Skip to content

Instantly share code, notes, and snippets.

@joaoportela
Created July 31, 2012 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaoportela/3219297 to your computer and use it in GitHub Desktop.
Save joaoportela/3219297 to your computer and use it in GitHub Desktop.
// -- 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
// -- 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