Programming Style Guidelines

Style leaves a large leeway to personal choice. As you develop your programming style, your choices may change. However, make sure you consistently apply the same style in one project (lab). Inconsistent use of a style is bad style. You may change your style in the next lab.

Header Comments

All files should have a set of comments at the top of the file:
// Adds two numbers- What the contents of the file are for
// Project #1 Add Program- The assignment name and class if the file is part of a class program assignment.
// CS 13011
// John H. Doe- Who wrote the program
// 9/14/99  - The date the program was created or last modified 

Identifiers

Identifiers (i.e. names for constructs you create in the program such as variables, constants, function names) should be selected so that they reflect their usage. If you cannot come up with a good name for the variable, or other construct, then you are probably unclear as to the operation of your program and you need to re-think it. The length (and descriptiveness) of an identifier is inversely proportional of its scope (the space in the program where it is used). That is, the smaller the scope the shorter the name of the identifier. If a certain variable is used in multiple places in the program its identifier should be long enough to convey the intended purpose of the variable and to remind the programmer what it is used for when it is encountered. However, it is a variable used to temporary store a value, for a few lines of code, then a short name, such as tmp is appropriate. For example:
	int tmp;
	
	// swapping values of a and b
	tmp=a;
	a=b;
	b=tmp;
	
Use CamelBack or c_style identifiers.

Declaring Variables

Variables should be declared as close as possible to where they are used and their scope should be as narrow as possible. Make the variable local to the block is is used in. Variables should be initialized (assigned value at declaration). The only exception should be the case where a variable is declared and immediately input a value. For example:

int n;
cin >> n;

Constants

Use named constants instead of literal constants. Named constants are more descriptive. For example, instead of:

int calc = 20 * 90;

Use:

const int numStudents = 20;   // number of students
const int lowestA = 90;	      // lowest score for A
int calc = numStudents * lowestA;
Named constant declaration rules are the same as variables: declare your constants as close as possible to first use, use the narrowest scope.

Use named constants instead of varables: if a variable is never updated except for initialization, make it a constant. For example: If

int calc = numStudents * lowestA;
is the only place where calc is updated. Turn this into a constant declaration:
const int calc = numStudents * lowestA;
Do not use preprocessor directive #define for named constants.

Comments

Comments in a program allow the programmer to clearly express the purpose of particular construct or portion of code. Comments should be written before or at the same time as the code itself. Writing comments afterwards "for the teacher" is bad programming practice and should be avoided. If you are struggling to annotate your code with comments, then it is possible that you are unclear on the purpose of the code itself and should re-think it.

Use the C++ style comments (//). Leave the C-style comments (/* ... */) for special purposes such as commenting out portions of code.

"Educational" comments explaining what the particular construct means in C++ (unless it is relatively obscure or not obvious) should be avoided. You can assume that the reader is familiar with C++. Use "production" comments that explain the purpose and intent of the code. For example:

++total; // increment total educational comment, avoid
++total;  // another element is processed production comment, use
Start every block of your program that does a separate function with a line of comments. Put an in-line comment on the side of some statement that you feel deserves extra explanation. Do not over-comment is it drowns out the code. Commenting every line of code is over-commenting.

Put an inline comment for every variable declaration (except for obvious cases such as loop variables used right after the declaration) explaining what this variable is for. Comment a function prototype. Put more extensive comments in front of a function definition, possibly explaining the purpose for the parameters and the function's return value:

//  sorts an array a[] using quicksort method
//  returns the smallest element
int qsort(int a[]){
   ...
}

Line Spacing, Line Length

Put a blank line between lines of code that contain a complete or somewhat independent action. This makes the program easier to read. For example, instead of:

// read in the valuesThese lines are hard to read.  It is hard to see what the different parts of the code are.
cout << "Enter ...";
int n1, n2;
cin >> n1 >> n2;
// calculate
int total = n1 + n2;
// print out the results
cout << "Total is " << total << '\n';

Use:

// read in the valuesThese lines are much easier to read.  The placement shows the different "paragraphs" of code.
cout << "Enter ...";
int n1, n2;
cin >> n1 >> n2;

// calculate
int total = n1 + n2;

// print out the results
cout << "Total is " << total << '\n';

Use line size of 75-80 characters: about the width of the text on a page in a book. Longer line sizes make the program hard to read.

Indentation

Indentation highlights the dependency between statements.

Sequential statements should line up:

int v;
cin >> v;
v *= 2;
cout << v;

Note return statement is a sequential statement. It should line up with the rest of the sequential statements.

Conditional statements should indent for the statements that they contain:

if (s < 0)
    cout << s; Indent then statement
else
    cout << (s * 2);Indent else statement

If you use braces (curly brackets) for a block of code in the conditional statement place them as follows:

if (s < 0 ) {
    ++s;	     indent then statements
    cout << s;
} else { 
    --s;     indent else statements 
    cout << tmp;
}	    

Multi-way if (if-else-if sequences of similar nature) should be indented as follows:

if (i==1) {
    i+=1;	then action of the first if indented
    cout << i;
} else if (i < 1) {
    i+=2;       then action of the second if indented
    cout << i;
} else if (i > 1) {
    i+=3;       then action of the last if indented
    cout << i;
}

switch should be indented as follows:

switch(i) {
case 1:
    i+=1;
    cout << i;
    break;
case 2:
    i+=2;
    break;
default: 
    cout << i;
}

Loop body should be indented as follows:

while (s > 0) {
    cin >> s; Indent inside loop body
    ++s;
}

Nested conditional and loop statements should be properly indented:

while (s < 0) {
    cin >> s; Indent inside loop body
    if (s < 0 ) {
       ++s;      Indent inside then-statements
       cout << s;
    }
}
Functions should be indented similar to loops:
int computeMax(int i, int j) {
   if (i > j)
      return i;
   else
      return j;
}

Protection Against Multiple Inclusion

Make sure to use include guards in your header files to protect against multiple inclusion. A good name for include guard variable contains the name of the header file:
#ifndef MYHEADER_H
#define MYHEADER_H
class MyClass {
 ...
};
const int myConst; 
#endif // MYHEADER_H

Classes

Start class and structure names with a capital letter. Function (standalone and method) names, except constructors and destructors, should start with a lower case. Use trailing underscore for private attribute name. If parameter is used to initialize the attribute, use the same name for parameter (without the trailing underscore) as for the attribute. In your class definition, declare public members first, then private.

Do not use void to signify lack of parameters in a function. Do not place a semicolon after inline function definition.

Here is an example:

class MyClass{
public:
   MyClass(){data_=0;} note, no trailing semicolon
   void set(int);
private:
   int data_;
};

void MyClass::set(int data){
   data_=data;
}

No Input Validation

Input validation is a process of ensuring that input is within expected constraints. For example, if the user is asked for an number between 0 and 99, then the input is indeed such a number and not, for example, a character. For this course, no input validation programming is required. The input is always assumed to be correct.
The style guide was originally compiled by Michael Collard, additions are due to Debbie Stoffer and others.