SI204 C++ Style Guide

Spring 2010

 

1.0 General

This style guide is mandatory for all submitted work for grading (homework, projects, labs, exams).    The purpose of the guide is not to restrict your programming but rather to establish a consistent style format for your programs. This will help you debug and maintain your programs, and help others (including your instructor) to understand them. As your programs grow in length and complexity, it is critical to use a consistent style. In the long run this will help you since one focus of this course is to build a foundation for later courses.  Points will be deducted from all submitted work unless it conforms to this style guide.

 

2.0 Visual Layout

You should format your program source code making use blank lines to separate code groups, functions and groups of logically related blocks.  Output from a program should be both informative and professionally formatted. A person reading the output should be able to determine whether the program works without knowing the internal details of the program. 

 

3.0 Indentation and Whitespace

Indentation is used to highlight the block structure of the code and should be used consistently. The proper use of whitespace and indentation makes the structure of the program evident from the layout of the code. You must use proper indentation, which in this class is the Visual Studio default.  Vertical whitespace is the use of blank lines to help set off blocks of code and increases readability of the program. Code with no vertical whitespace is difficult to follow.

 

No line of code should wrap beyond the right margin. If a line of code becomes too long, break it up into pieces. Remember the compiler largely ignores extra whitespace in your programs (but be careful with strings).

 

The only thing that may follow an opening brace ‘{on a line of code is a comment. The block of code enclosed by a set of braces must be indented one level inside the enclosing braces. With one exception discussed later, a closing brace must always be on a line by itself and must be at the same level of indentation as the line containing the corresponding opening brace.

 

3.1 Comments

Comments should be indented consistently with the block of code they describe. Comments can be divided into two general categories, strategic and tactical.

 

Strategic comments are used to give the reader a general overview of what is going on. These comments appear at the beginning of files. Strategic comments tend to be written in sentences with an emphasis on explaining the big picture of what the block of code is designed to do.

 

Tactical comments are designed to explain tricky areas of code, what parameters do, and hints about the control flow of the program. These comments should be intermixed in the code when needed. They should be shorter than strategic comments, in bullet format, and may be in inline format.

 

If you use sensible and informative naming, block structure, indentation, and straightforward programming, your code will be mostly self-documenting. This is what you should strive for. Keep comments simple. Do not attempt to explain what is obvious from the code itself.

 

Numerical constants must have a comment explaining the value if it is not self-evident.

 

The following two examples show a program that conforms to the style guide and a program that produces the same result but does not conform to the style guide.  It is clear that the conforming program is much easier to understand.

 
// Example 1. This program conforms to the style guide
 
int main()
{
  // read input “Time Elapsed xxx “ where xxx is total seconds
  string junk;
  cin >> junk; // reads (and ignores) the word "Time"
  cin >> junk; // reads (and ignores) the word "Elapsed"
  
  int timeIn;
  cin >> timeIn;   // reads the time in seconds
 
  // convert timeIn to minutes and seconds
  int minutes, seconds;
  minutes = timeIn / 60; // determine # of whole minutes in timeIn 
  seconds = timeIn % 60; // determine # of seconds after last whole minute
 
  // write out result
  cout << "Time Elapsed " << minutes << " minutes and " 
       << seconds << " seconds" << endl;
 
  return 0;
} // end main

 

 

// Example 2. This program DOES NOT conform to the style guide. 
// Points will be deducted for code like this even if the program code 
// produces correct output!  Note the poor use of variable names,
// whitespace, indentation, and lack of strategic and tactical comments.
 
int main()
{ string junk; cin >> junk;
  cin >> junk; 
int a;
    cin >> a;
  int b, c; b = a % 60;
  c = a / 60;
  cout << b << c << endl;
  return 0;  }

 

 

3.2.1 File Headers

Each file must have a descriptive comment header block at the beginning as follows:

 

//*************************************************************

//     File:             ___________ <name of this file, .h or .cpp>
//     Name:          ______________ <your name>
//     Project or HW or Lab name ___________
///    Date:           ___________
//     Description: A brief description

//*********************************************************************

 

 

4.0 Control Structures

The use of braces is required (for style purposes, not necessarily syntax purposes) for all control structures, including those with a single statement in the body. Avoid the overuse of continue and break in loops. Always use a default case in switch statements. Use a break statement to end all cases (including default) in a switch statement. Conclude the closing brace ‘}’ of all compound statements with a comment stating what the brace marks the conclusion of. This will greatly aid in figuring out what to do if your compiler reports that you have mis-matched opening and closing braces.

 

Place the opening brace of a block of statements on the line following the statement to which it belongs. Indentation and formats for control structures are as follows:

Text Box: The if-else statement:
if (boolean expression)
{
//statement(s);
}	
else   
{    
  //statement(s);
}…..
Text Box: The nested- if statement:
if (boolean expression)
{
//statement(s);
}	
else if (Boolean exp)  
{    
  //statement(s);
}…..
Text Box: The if statement:
if (boolean expression)
{
//statement(s);
}

 

 

 

 

 

 

 

 

 

 

 

The for statement:

for (expression; expression; expression)

{

//statement(s);

}    //end for <optional comment>

 

 

The do/while statement:

do

{

//statement(s);

}   while (boolean expression)

 

The while statement:

while (boolean expression)

{

//statement(s);

}   //end while <optional comment>

 

 

The switch statement:

switch (expression)

{

case <constant expression>:

       {

//statement(s);

break;

}

case <constant expression>:

       {

//statement(s);

break;

}

      default :

            {

            statements(s);

            }

}// end switch <optional comment>

 

5.0 Naming

Variables must have meaningful names/identifiers. For example, consider a program that uses a variable to track the yards per carry of a football game.  Such a variable should be called yardsPerCarry vice ypc for program readability. This must be balanced against using names which are too long, which can obscure the code. (Fifteen or so characters approaches the “too long” limit.)

 

Single letter variables or constants should not be used with the following exceptions. An exception to this rule is when it is common practice to identify something with a single letter. An example of this is the coordinate system (X, Y, and Z). A second exception occurs in the use of loop counter variables where it is common practice to use variables like i and j as counters in for loops.

 

Function names and variable names should begin with a lower case letter. An identifier consisting of multiple names SHALL have each name distinguished by making the first letter of each name part upper case (e.g. yardsPerCarry) or by using underscores (yards_per_carry). Constants should be named in all upper case letters. Example:

 

    const int PI = 3.14;

 

Do not use the lower case letter ‘L’, or the letter ‘O’ in names unless they are part of normal words. This is to avoid confusion with the numbers 1 and 0. For example, is “cell” c- e - 1- ONE or c- e- 1-1?

 

Avoid names that differ only in case, look similar, or differ only slightly. For example, InputData, InData and DataInput will certainly be confusing if used in the same program.

 

Names of functions should reflect what they do (printArray), or what they return (getAge). Boolean variable names should sound like Yes/No things — “isEmpty” and “isFinished” are possible examples.

 

 

6.0 Miscellaneous but Important Stuff

Always use the most appropriate operator or construct for the work you want it to do. Good design and clarity take precedence over optimization. Do not declare or use more variables than are necessary.

 

Numerical constants (“magic numbers”) must not be coded directly. The only allowable exceptions are for 0, 1 or -1, and those which are not “likely” to change; for example code determining if a number is even can use the number “2” since it is not likely to change. Numerical constants must have a comment explaining the value if it is not evident from the name.

 

You should test doubles (or floats) with <= or >=.   Never use exact comparisons with floating point numbers, even when comparing to 0.0 as floating point numbers such as 1/3 are stored as a highly accurate, but nonetheless approximate values. The appropriate means of comparison is to define a value (in

engineering lingo, “epsilon” ) that represents the maximum difference by which two values may differ and still be considered equal.

 

Test your code. It should produce the correct results for normal test conditions as well as boundary conditions like short or empty lists.  Get in the habit of saving (under a different filename) a partial, but working, early version of your program as you progress thru your software development.  That way, if you muck your program up in a night of caffeinated binge coding, you will have a few prior versions to consider restarting from should you feel the need to throw out the problem code.  In extreme cases, consider restarting from scratch as it is sometimes easier to begin anew instead of slugging away trying to straighten out poorly designed source code.

 

DO NOT modify project, lab, exam, or homework specifications without explicit permission from your customer (the instructor)!  Even if you think you have explicit permission to modify project specifications, modifications from the written assignment must be clearly and completely documented in your code and in your project documentation.