Programming Style Guide

Program Comments: A well-written computer program in a high level language, such as C/C++, is said to be "self-documenting". Through the use of meaningful identifiers and logical flow of computer instructions, a program you write should be "readable" to another programmer. However, a programmers intention of what the program does and how the program does it are not always easy to see by looking at the program. That is why it is important to include comments in your programs.

The style of your comments includes where you put comments in your program and what you say in those comments. There are many different comment styles. You should follow the one described below, unless your instructor indicates differently. The elements that are considered essential to your programming are emphasized by "must".

File and program header comments: Each program that you write must have a comment at the beginning of the program that is called "a header" or "header comment". This must include the following information: Your name, the date, the name of the file the program is stored in, a description of the program and usage (how to run it).

Example:

// File: prog1.cpp
// Name: Martha Reeves
// Date: 8/13/99
// Course: CS 150 - Introduction to Computing II
// Desc: Program calculates mean, standard deviations, and variance for a
//       set of numbers.
// Usage: The program reads from a text file containing one number per line.
//        The program prompts for and reads the name of the file.

As you develop your programming skills, you will divide your program into different files called modules. Each file must also contain a header comment that includes your name, the date, the name of the file in which the code is stored. You should also indicate what other files the module depends on.

Example:

// File: prog4.cpp
// Name: Martha Reeves
// Date: 8/13/99
// Course: CS 150 - Introduction to Computing II
// Desc: Program reads in a students course information into an array of courses. It
//       calculates gpa and quality points. It then prints our a course report of the
//       students credit hours, grade, quality points and gpa.
// Usage: The user types in one positive number. Other files required: course.cpp, course.h

An example of a header comment for a file containing a class implementation:

//   File: fraction.cpp
//   Name: Martha Reeves
//   Date: 8/13/99
// Course: CS 150 - Introduction to Computing II
//   Desc: This module exports a Fraction class which represents numbers as a numerator
//         and denominator. Basic math operators implemented: *,/,+,-, and unary -. Math
//         operators are implemented for mixed mode operations with integer or double
//         data types. It also exports stream insertion and extraction operators.
//
//         Other files required: fraction.h, math.h, iostream.h

Function header comments: A complex program is always broken into smaller sub-programs. In C/C++ these are called functions. Each function is responsible for performing one particular task. Each function must also have a header comment. The function header must include a description (what the function is supposed to do), pre conditions (what the function expects and assumes in order to run correctly), post conditions (what changes does the function make, what, if any, value does the function return).

Example:

// Function: QualityPoints
//
// Desc: Function calculates a students quality points for a course.
//       The quality points are calculated by multiplying the students
//       grade with the number of credit hours for the course.
//
// Pre: The function requires the character value of the students grade.
//      It assumes the grade will be A, B, C, D, or E and a 4 point grading
//      scale.
//
// Post: The function returns the quality points as a floating point value.

An alternative function header you may use, which I prefer is:

//-----------------------------------------------------------------------
// Function:      QualityPoints()
//
// Parameter:
//     In:        char cGrade - the letter grade for the course
//                int iCreditHours - the course credit hours
//     Out:       none
//     In/Out:    none
//
// Returns:       the quality points for the course
//
// Desc:          multiplies the credit hours by the course weight.
//-----------------------------------------------------------------------

Inline and block comments: Beside header comments, you will also need to include some comments in the body of your programs. There are two types of comments that can be included: inline comments and block comments. Inline comments are short comments that are interspersed through your program code or on the same line as a program instruction. Block comments are like the header comments, they explain what an entire section of your code is supposed to do.

DO NOT OVER COMMENT. You should try to write your programs in such a way that another programmer could understand it. Too many comments get in the way of reading a program. For this reason, you should use inline comments sparingly. Beginning programmers have a tendency to use inline comments that explain very obvious lines of code.

An example of what NOT to do:

sum = sum + 1 // incrementing sum by one

You will write a group of program instructions that perform a specific action called a block of code. In C/C++, a block of code is indicated by an opening and closing brace - {}. One good use of inline comments is to add a short comment behind a closing brace that indicates the block of code it terminates.

Example:

#include <iostream.h>
void main(void)
{
    int i;
    int sum=1;
    int product=1;
    for(i = 2; i <= 10; i++)
    {
        sum = sum + i;
        product = product * i;
    } // end for
    cout <<"The sum of integers from 1 to 10 is "
         << sum << endl;
    cout <<"The product of integers from 1 to 10 is "
         << product << endl;
} // end of main

White Space and Indentation: C/C++, like other programming languages, is free format. This means that you can write program instructions one after another without putting any spaces between them. In fact, if you had a mind to, you could write an entire program in one long line. Of course, this makes it difficult to read and understand. Therefore, you should try to format your programs so that they are "readable" (See Appendix A for an example of a difficult to read program).

One way you can make your programs more readable is to follow some simple rules of indentation. Program instructions in the same block of code must be on the same level of indentation. Anytime a block of code is inside another block of code (this is called nesting), then the inside block (nested block) must have one additional level of indentation. In the example above, the for statement is indented one extra level, and the program instructions of the for loop are indented one extra level. Each level of indentation should be 3 to 5 spaces (if you use more, then deeply nested blocks tend to run off the right margin of the page). Besides indenting a block of code, you should align the opening and closing braces.

The example below has multiple nested blocks of code: the if -else statement is nested within the for loop statement, and a while loop statement is nested in the if and else statements. Note that each additional level of nesting has an additional level of indentation to distinguish it, and that the opening and closing braces are aligned.

Example:

for (int k = 1; k <= endPoint; k++)
{
    if (k < (endPoint / 2))
    {
        m = 1;
        while (m <= (endPoint / 2))
        {
            cout <<*;
            m++;
        } // end while
    } // end if
    else
    {
        m = 1;
        while (m <= endPoint)
        {
            cout <<*;
            m++;
        } // end while
    } // end else
} // end for

In addition to indentation, a judicious use of blank lines can also make your programs more readable. Put a blank line between blocks of code and 3 or 4 blank lines between functions. As you gain programming experience, you will find that functions of a well-written program are no longer than one page. You should to format your listing so that functions are not split between two pages. Consult with your instructor about his/her preference concerning the placement of page breaks in your source code.

Mnemonic Names: A variable is a memory space that you will use to store values in your program. Both variables and functions require names (also called identifiers). The name of a variable must indicate what the value it is storing represents. For example, a variable that holds a students grade could be called: courseGrade.

The name of a function should indicate the task that the function performs. In general, a function that returns a single value should be named with a noun indicating what the value represents. A function that performs some action should be named with a verb indicating the nature of the action. Names of functions that perform Boolean checks (return a true or false) should indicate the nature of the test. In the example code segment below, "ReadInformation" is a function that obtains all the necessary information for a single course, "ValidLetterGrade" is a Boolean function that checks to see if the value of courseGrade is one of the acceptable letter grades, and "QualityPoints" is a function that returns the number of quality points earned for a course given the letter grade. Note how much information about a function is conveyed by a good name without even knowing anything else about it.

do
{
    ReadInformation(courseGrade,courseName,numberOfCreditHours);
    if (ValidLetterGrade(courseGrade))
        totalQualityPoints = totalQualityPoints + QualityPoints(courseGrade);
} while (ValidLetterGrade(courseGrade));

Other, more strict, naming conventions exist. One example is called "Hungarian". In this style, quantifiers are added to the front of names to indicate that they are of the same type of values. For example, if your program had integers indicating the coordinates on a graph, the row coordinates would be preceded by the prefix "row" and the column coordinates would be preceded by the prefix "col"; so you might have the variables: rowStartPoint, rowEndPoint, colStartPoint, colEndPoint.

There are different styles for putting words together to form identifiers. The one above used capital letters to indicate the beginning of a word in an identifier. Another style is to use an underline character between words, like Valid_Letter_Grade or course_Grade. You should consult your instructors as to their preferences to naming conventions.

Programming Style: As you become an experienced programmer, you will find that each programming language you use will in some ways restrict the way you use program instructions and variables, yet still allow you quite a bit of flexibility. How you use that flexibility will define your programming style. There is no one style that everyone agrees is the best, but there are a few principles that we would like you to follow.

DO NOT use the goto instruction (unless your instructor says it is o.k.).
DO NOT use global variables (unless your instructor says it is o.k.).
DO NOT use a break statement to exit from a loop (unless your instructor says it is o.k.).

Appendix A
An example of a difficult to read C program.

int i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hello, wor\
ld!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);}

Yes, this is a real program that compiles and runs. The program writes "hello, world!" to the screen. Even the simplest of programs can be difficult to understand if your programming style is poor. This program was one of the winners of the 1984 International Obfuscated C Code Contest.