Originally Posted by
msh
It's always harder to read the code then to write it, and I see it as a
very important skill to have.
I don't claim to be any good at it, but there are several things I do when I'm reading the code of others: (1) run it through a code formatter, (2) delete all the comments and (3) add my own comments as I read the code and try to make sense of it.
(1) is optional, and I only do it if the code is poorly formatted or the style is too far different from my own. Reason for (2) is that people like to comment what the code does, not what the intent is. Comments like that are only useful for a particularly involved code. Otherwise I prefer that people document their intent. This might be a personal quirk.
(3) is because
really I like to make notes. You wouldn't believe the amount of notes I have scribbled in the margins of various books I've read.
Well, I'm not a scribbler... but I do agree that people should comment on what their code is trying to accomplish not what the C function does... "//open dorsal airlock" tells me a lot more than "//set bit 7" which should be obvious from the code itself.
Coming from a Pascal background I never really got into the K&R way of formatting code. My C code looks like Pascal source and I've been chastized about it a couple of times. The problem is that I'm so used to seeing code a certain way, I find the K&R style very hard to read.
Here's a windows code example from a project I'm working on...
Code:
// types list initializer
VOID InitTypesList(HWND Dlg)
{ TVINSERTSTRUCT tvi = {0}; // tree view item struct
TCHAR tvt[MAX_TYPENAME] = {0}; // item name
DWORD idx = 0; // enum index
HTREEITEM tvh; // current item
HKEY reg; // association registry key
// get treeview handle
hTree = GetDlgItem(Dlg,4001);
// make sure it's empty
TreeView_DeleteAllItems(hTree);
// precondition struct
tvi.hInsertAfter = TVI_SORT;
tvi.item.mask = TVIF_TEXT;
tvi.item.cchTextMax = MAX_TYPENAME;
tvi.item.pszText = tvt;
// enumerate type keys
while ( RegEnumKey(REG_RHIVE,idx,tvt,MAX_TYPENAME) != ERROR_NO_MORE_ITEMS)
{ if (tvt[0] == L'.')
{ tvh = TreeView_InsertItem(hTree,&tvi);
// check file association
if (!AssocQueryKey(ASSOCF_NOFIXUPS | ASSOCF_INIT_IGNOREUNKNOWN,
ASSOCKEY_CLASS,tvt,NULL,®))
{ if (!SHGetValue(reg,REG_RMDATA,NULL,NULL,NULL,NULL))
TreeView_SetCheckState(hTree,tvh,TRUE);
RegCloseKey(reg); } }
++ idx; }
// set initial item
TreeView_SelectItem(hTree,TreeView_GetRoot(hTree));
SetFocus(hTree); }
Apparently this drives some C programmers to distraction. But I find it to be very compact and easily followed, especially with syntax color highlighting turned on. I also realize this is part of why I find other people's code so hard to follow... it doesn't look right to me.
Curiosity got framed, IMO. Ignorance killed the cat!
LOL... cats have no plan.