Commenting Practices and General Coding Style


Making comments is not suppose to be busy work. Comments usually serve a functional purpose.


Lets look at some professional examples of commenting




Id Software: Quake III (Full source code github.com/id-Software/Quake-III-Arena/)


/*

==============

BotUpdateInput

==============

*/

void BotUpdateInput(bot_state_t *bs, int time, int elapsed_time) {

bot_input_t bi;

int j;


//add the delta angles to the bot's current view angles

for (j = 0; j < 3; j++) {

bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j]));

}

//change the bot view angles

BotChangeViewAngles(bs, (float) elapsed_time / 1000);

//retrieve the bot input

trap_EA_GetInput(bs->client, (float) time / 1000, &bi);

//respawn hack

if (bi.actionflags & ACTION_RESPAWN) {

if (bs->lastucmd.buttons & BUTTON_ATTACK) bi.actionflags &= ~(ACTION_RESPAWN|ACTION_ATTACK);

}

//convert the bot input to a usercmd

BotInputToUserCommand(&bi, &bs->lastucmd, bs->cur_ps.delta_angles, time);

//subtract the delta angles

for (j = 0; j < 3; j++) {

bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j]));

}

}



Google: An HTML 5 parser (Full source code https://github.com/google/gumbo-parser)


// Returns true if the given needle is in the given array of literal

// GumboStringPieces. If exact_match is true, this requires that they match

// exactly; otherwise, this performs a prefix match to check if any of the

// elements in haystack start with needle. This always performs a

// case-insensitive match.

static bool is_in_static_list(

const char* needle, const GumboStringPiece* haystack, bool exact_match) {

for (int i = 0; haystack[i].length > 0; ++i) {

if ((exact_match && !strcmp(needle, haystack[i].data)) ||

(!exact_match && !strcasecmp(needle, haystack[i].data))) {

return true;

}

}

return false;

}

Note that both of these examples are not describing every detail but the overall logic of the code.

They serve a purpose of describing what the function does without needing to how.

They also help you think through the expected input and output of the function.

You should be able to write almost all your comments before you write any code.