Wednesday, November 10, 2004 11:23 AM
LarryOsterman
What does style look like, part 2
In my previous style post, I took a piece of code from Robert Sedgewicks algorithms book, and "Hungarian-ized" it. The routine currently looks like:
#include "list.h"
main(C cArg, SZ rgszArg[])
{
I iNode, cNodes = atoi(rgszArg[1]), cNodesToSkip = atoi(rgszArg[2]);
PNODE pnodeT, pnodeCur; InitNodes(cNodes);
for (iNode = 2, pnodeCur = PnodeNew(1); iNode <= cNodes ; iNode++)
{ pnodeT = PnodeNew(i); InsertNext(pnodeCur, pnodeT); pnodeCur = pnodeT; }
while (pnodeCur != PnodeNext(x))
{
for (iNode = 1; iNode < cNodesToSkip ; iNode++) pnodeCur = PnodeNext(pnodeCur);
FreeNode(PnodeDeleteNext(pnodeCur));
}
printf("%d\n", Item(nodeCur));
}
Btw, I'll show what this code looks like without hungarian during this series, don't worry :).
Now that it's hungarianized, lets look at the structure. The first thing that stands out is that it's not completely consistent. Every indentation is 2 spaces, but sometimes lines are compressed, sometimes not. This is undoubtedly a concession to the space requirements in the book, it's not likely something you'll find in production code.
Lets re-format the code and see what happens. First, I'll use the "braces appear on the same line as the conditional, indented 4 characters (K&R)" style:
#include "list.h"
main(C cArg, SZ rgszArg[]) {
I iNode, cNodes = atoi(rgszArg[1]), cNodesToSkip = atoi(rgszArg[2]);
PNODE pnodeT, pnodeCur; InitNodes(cNodes);
for (iNode = 2, pnodeCur = PnodeNew(1); iNode <= cNodes ; iNode++) {
pnodeT = PnodeNew(i); InsertNext(pnodeCur, pnodeT); pnodeCur = pnodeT;
}
while (pnodeCur != PnodeNext(x)) {
for (iNode = 1; iNode < cNodesToSkip ; iNode++) pnodeCur = PnodeNext(pnodeCur);
FreeNode(PnodeDeleteNext(pnodeCur));
}
printf("%d\n", Item(nodeCur));
}
To me, the code hasn't changed that much. Lets make another change: Moving each statement to its own line:
#include "list.h"
main(C cArg, SZ rgszArg[]) {
I iNode, cNodes = atoi(rgszArg[1]), cNodesToSkip = atoi(rgszArg[2]);
PNODE pnodeT, pnodeCur;
InitNodes(cNodes);
for (iNode = 2, pnodeCur = PnodeNew(1); iNode <= cNodes ; iNode++) {
pnodeT = PnodeNew(i);
InsertNext(pnodeCur, pnodeT);
pnodeCur = pnodeT;
}
while (pnodeCur != PnodeNext(x)) {
for (iNode = 1; iNode < cNodesToSkip ; iNode++)
pnodeCur = PnodeNext(pnodeCur);
FreeNode(PnodeDeleteNext(pnodeCur));
}
printf("%d\n", Item(nodeCur));
}
That's somewhat better, the routine takes some more vertical space, but it's a bit clearer what's going on.
Tomorrow, BSD style, and a bunch of other indentation varients.