C++ Coding Standards

Every program must begin with a block of comments:

/*
* Terry Harvey and Xenon Qzwik, CISC181H Spring 09, TA: Matt Fendt
*
* Draws ASCII diagonal lines with asterisks.
* INPUT: prompts for user input
* EFFECTS: prints to cout
*/

At a minimum, these comments must include name, date, class, TA, and section number, along with a brief description of what the program does. If the program is related to a particular assignment, the assignment and problem number must be included. If the program uses a particular algorithm for solving a problem, that must be stated also.

 

Functions must begin with a block of comments. The only exception to this rule would be trivial one or two line functions whose names would make their function clear to someone new to the code. These are very rare in practice - so comment.

/*
* Uses binary search algorithm to locate key in a sorted array.
* INPUTS: sorted array, 0, size-1, key
* RETURNS: integer index of key in sorted array, or -1 if not found
* EFFECTS: none
*/
int binarySearch(int sorted[], int start, int end, int key);

Good naming is difficult. A name should indicate the purpose of the item being named. However, naming an int variable "intVar" does not add any useful information, so follow the programming conventions used in class if you cannot use a better name like "input" or "radius" or "continueFlag".

Do not use comments to make up for using bad names. Spend time on the names instead. Comments should only point out special features of your code, or be used to isolate major sections visually (though this is often better accomplished with whitespace).

Here is bad commenting for bad naming:

int n; //n is an integer for input

Here is better code that doesn't need commenting:

int input;

Here is bad commenting for bad naming:

int    input1, //is the radius
        input2; //is the width

Here is better code that doesn't need commenting:

int radius,
    width;

If you aren't sure, ASK!

  1. Useless or incorrect comments may be penalized. Example:

    for (i=1; i<=100; i++) //loop one hundred times

  2. Names for all variables and functions must clearly indicate their purpose, with the few exceptions for variable names discussed in class. If you are not sure about an abbreviation's readability, don't use it. Use underscores or camel notation (e.g. getCylinderWidth()) to separate multiple words.
  3. Defined or declared constants, and only defined or declared constants, will be named with all caps. Use underscores to separate multiple words in constant names.