C++ Formatting Rules

The formatting rules for programming assignments are actually for all programming assignments and not just C++. However, the syntax shown in these examples are from C++. You should take the “spirit” of formatting and documenting programs to every language you use.

The C++ Formatting Standards given below are to be used in this course. These standards have been approved by the department and are required for all programming assignments.

C++ allows for the use of free formatting and multiple statements per line. The excessive misuse of this, however, can lead to a program which is difficult to read. You should quickly adopt good habits of indentation to enhance the readability of your program and to highlight its logical structure.

There is no single ``industry standard'' for formatting C++ programs. Nonetheless, a guide for pretty printing is provided below for you to follow.

The General Rules

The rules in this section provide a frame of mind that you should take on when writing your program and considering the commenting and variable names you create. Remember the variable names and comments provide documentation of what your program is doing and why it is solving the problem in that particular manner.

1.  Each program must begin with a comment which identifies the program and the programmer. It should be formatted according to the following example:

//   CIS 121 Section 01

//   Assignment No. 1

//

//   Smith, Rosalynn

//   SSN 6789 (last 4 digits only)

//

//   This program takes as input the sale price and the

//   percentage reduction of a sale and outputs how much money

//   one saves when she buys an item on sale.

 

2.     Use additional comments to ``Paragraph'' your C++ program in such a way that one can visually identify the logically related modules of the program. Use at least one blank line between modules.

3.     Use comments that tell what or why something is being done, not how it is being done. Comments should be in simple English and be directed towards explaining the higher level algorithmic functions being performed.

4.     Use meaningful identifiers for variables, types, procedures, and functions. For example, s, d, p should be replaced by names such as Sales, Discount, and Price.

5.     The spacing of any construct not specifically mentioned in this standard is left open to the user. The user is encouraged to insert extra blank lines beyond those given in this standard to promote readability. (see example code in Example Formatting)

6.     Each statement must begin on a separate line. All { and }'s must appear on separate lines except for comments. Each } must be indented to the same level as it's matching {. (see example code in Example Formatting)

7.     Each line must be less than or equal to 72 characters. Warning: just because it looks okay on your screen doesn't mean it will look good on others. Always type a return at the end of every line.

8.     Use a modest amount of indenting per line. 3-4 spaces suffice. Do not use tabs. If your lines are indented so far over they no longer reasonably fit, it's time to create a function. (see example code in Example Formatting)

9.     Comments that are appended to the end of a line of code and that are continued on successive lines must be written so that continued line starts under the initial comment fragment. Similarly with long statements such as assignments that need to be broken up. E.g.,

foo = blot * rot - 78;  // Compute new value based on

                        // previous inputs.

10.   At least one blank line must appear before declarations. At least three blank lines must appear before function and class declarations.

11.   At least one space must appear before and after ``='' (assignment) and all two character operators (except ``->'' which may not have any spaces as well as ``.''). At least one space or newline must appear before and after each reserved word (except for) and before and after ``//'' in a comment

 

Rules for Declarations

Constant definitions and variable declarations are to appear in a ``data dictionary'' format. Each variable declaration should be on a separate line. Each line will include a comment specifying the usage and the meaning of each identifier. Note that this especially includes parameters to functions. Declarations should be formatted according to the following example:

// Constants:

  const int ArrayLength = 50;  // Size of array

// Variables (or objects):

  int ArrayIndex,             // Indexes into sort array 

      DayCount;               // Day of week counter 

  float Temp;                 // Temporary variable 

  char* Name;                 // User's name.

 Note that it is char* Name and not char *Name.

Control Structures

Contrtol structures and functions are used to create “paragraphs” in your program. There are some rules about using them from a formatting point of view just like with paragraphs in English.

1.       Goto's are not allowed unless there is no other way to do the task.

2.       Nesting of any combination of if, for, while and switch statements must be no more than four levels deep.

while (…) { // level 1

   if (…) { // level 2

      while (…){  // level 3

           while (…) {  // level 4 (deepest)

          

           }

      }

   }

}

If your code seems to require more levels then rewrite the program. Perhaps make the inner 2 levels into a function, and then they can be replaced with a function call.

3.       All lengthy (more than 6 lines) loops and switches must have a comment after the last brace such as:

for (…) {

… more than 6 lines of code

} //end for ...

Rules for Functions

Each function must be preceded by a comment which describes the purpose of the program module. The following is a reasonable example:

/* 

  Name: name of function

  Description: a succinct function description, avoid     wordiness and redundancy

  Parameters:

    <name1>: description of first parameter

    <name2>: <and likewise for each parameter>

  Return:  <description of the return value>

*/

Real example:

/* 

  Name: FindAverage

  Description: Computes the average of 2 parameters

  Parameters:

    num1: The first number

    num2: The second number

  Return:  The average

*/

float FindAverage(float num1, float num2) {

}

Example Formatting

The purpose of this section is to demonstrate good formatting vs bad formatting. The hope is that you will model your formatting after the good examples, and that you can see why the bad examples have poor formatting.

A well formatted program:

// CIS 121 Section 01

// Assignment No. ?

//

// Boop, Betty

//

// This program computes a class average based on the grades // given by the user.

#include <iostream>

 

using namespace std;

 

// function main begins program execution

int main()

{

   int total;        // sum of grades input by user

   int gradeCounter; // number of grade to be entered next

   int grade;        // grade value

   int average;      // average of grades

 

   // initialization phase

   total = 0;          // initialize total

   gradeCounter = 1;   // initialize loop counter

 

 

   // processing phase

   // gradeCounter counts the number of grades entered by the

   // user until 10 grades are entered

   while ( gradeCounter <= 10 ) {      

      cout << "Enter grade: ";         

      cin >> grade;

 

      total = total + grade;            // add grade to total

      gradeCounter = gradeCounter + 1;  // increment counter

   } // end while

 

 

   // termination phase: compute average

   average = total / 10;

 

 

   // display result

   cout << "Class average is " << average << endl; 

 

   return 0;

 

    } // end function main

Notice that the statements in the function are indented to the same level. The statements in the while loop are indented to another level. The comments of this code explain WHY the code was written, not just what it is. Also, note that the “paragraphs” of the code are identified as phases. You do not have to name the phases, but it makes the code clearer.

Commenting and formatting is somewhat of an art. You should pay attention to how comments are written in the code given in textbooks and other resources for guidance.

.
.
.
.
.
.
.
.
.

 

 

.
.
.
.
.
.
.
.
.