How To Document and Organize C or C++ Code

Adapted from Edward Parrish's C++ coding standards:

On This Page


1. Introduction

Programming style is about how you organize and document your code. A program written following a consistent style is easier to read, easier to correct and easier to maintain.

A program may be written only once, but is read many times:

  • During debugging
  • When adding to the program
  • When updating the program
  • When trying to understand the program

Anything that makes a program more readable and understandable saves lots of time, even in the short run.

Most programmers agree that coding standards are important. The problem is that there is no single standard for C or C++. As a professional programmer, you must be prepared to adapt your style to the standards of your company or project.

This style guide follows often-used industry coding standards.

2. Naming Conventions

2.1. Use Meaningful Names

Choose names that suggest their purpose. Good names help you understand the problem you are solving.

2.2. Variable Names

There are two commonly-used styles you may use. However, you must be consistent and only use one of them in a program. The instructor's preference is the first style.

  1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
    int myVar
  2. Use all lower case letters and use underbars ('_') as separators.
    int my_var

2.3. Constant Names

Use all capital letters and use underbars ('_') as separators.

const int MY_CONST = 1;

2.4. Function Names

There are two commonly-used styles you may use. However, you must be consistent and only use one of them in a program. The instructor's preference is the first style.

  1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
    int myFunction()
  2. Use all lower case letters and use underbars ('_') as separators.
    int my_function()

2.5. Class Names (C++ only)

Start with an upper-case letter and use uppercase letters as separators. Do not use underbars ('_').

class MyClassName

3. Comments

Comments are explanatory notes for the humans reading a program. With good name choices, comments can be minimal in a program. The only required comments are block comments at the beginning of each file and before each function declaration. Block comments are described in the next section.

One other time to add comments, other than block comments, is when your code is unusual or obscure. When something is important and not obvious, it merits a comment.

3.1. Block Comments

doxygen is a tool that examines the declarations and documentation comments of your code to produce a set of HTML pages. The pages produced by this automated documentation tool describe your code to other programmers. For an example of the documentation produced, see this simple commented C program example.and the documentation produced by doxygen.

The documentation comments are derived from block comments, which you create as follows:

  • Indent the first line to align with the code below the comment.
  • Start the comment with the begin-comment symbol (/**) followed by a return.
  • Start subsequent lines with an asterisk *. Indent the asterisks with an additional space so the asterisks line up. Separate the asterisk from the descriptive text or tag that follows it.
  • Add a description of the purpose of the class or function.
  • Insert a blank comment line between the description and the list of tags, as shown.
  • Insert additional blank lines to create various tags (keywords starting with @).
  • The last line begins with the end-comment symbol (*/) indented so the asterisks line up and followed by a return. Note that the end-comment symbol contains only a single asterisk.
  • /**
    * @file expressions.c
    * @brief Prints results of various expressions to the screen.
    *
    * @author Ed Parrish
    * @date 02/02/04
    */
  • For thorough information on the tags, see the doxygen Special Commands.

3.2. File Comment Block (File Header)

Every source file must have a comment block at the top containing the name of the file and purpose of the file.
One or two lines is usually sufficient to explain the purpose. In addition, you must add the author tag containing your name and the version tag containing the date the code was written. For example:

/**
* @file peapod.c
* @brief Peapod program with annotated errors
*
* @author Ed Parrish (adapted from textbook)
* @version 1.0 8/20/03
*/

The following tags must be used always:

  • @file
  • @brief
  • @author
  • @date

3.3. Function Comment Block (Function Banner)

Every function must have a comment block before the function prototype declaration. For example:

/**
* @brief Calculates and returns the hat size.
*
* @param height The height in inches.
* @param weight The weight in pounds.
* @return The hat size in inches.
*/
double calcHatSize(double height, double weight);

The first line is a description of how to use the function.

Where appropriate, the following tags must be used:

  • @param
  • @return

3.4. Example Program Documentation

The following short program shows a brief example of properly-documented source code.

/**
* @file sphere.cpp
* @brief Calculates the area of a circle and the volume
* of a sphere.
*
* @author Ed Parrish
* @date 03/17/04
*/

#include <iostream>
#include <cmath>
using namespace std;

const double PI = 3.14159;

/* Function prototypes */

/**
* @brief Returns the area of a circle with the specified radius.
*
* @param radius The radius of the circle.
* @return The area of the circle.
*/
double area(double radius);

/**
* @brief Returns the volume of a sphere with the specified radius.
*
* @param radius The radius of the circle.
* @return The volume of the sphere.
*/
double volume(double radius);

int main(void)
{
double radius_of_both, area_of_circle, volume_of_sphere;

cout << "Enter a radius to use for both a circle\n"
<< "and a sphere (in inches): ";
cin >> radius_of_both;

area_of_circle = area(radius_of_both);
volume_of_sphere = volume(radius_of_both);

cout << "Radius = " << radius_of_both << " inches\n"
<< "Area of circle = " << area_of_circle
<< " square inches\n"
<< "Volume of sphere = " << volume_of_sphere
<< " cubic inches\n";

return 0;
}

/* Returns the area of a circle with the specified radius. */
double area(double radius)
{
return (PI * pow(radius, 2));
}

/* Returns the volume of a sphere with the specified radius. */
double volume(double radius)
{
return ((4.0 / 3.0) * PI * pow(radius, 3));
}

4. Curly Braces

A fervent issue of great debate in programming circles is placement of curly braces. Either of the following two styles is acceptable:

  1. Place brace under and inline with keywords:
    if (condition)
    {
    ...
    }

    while (condition)
    {
    ...
    }
  2. Place the initial brace on the same line as the keyword and the trailing brace inline on its own line with the keyword:
    if (condition) {
    ...
    }

    while (condition) {
    ...
    }


- The first style is more frequently used for C++ and the modern family of languages derived from C (Java, C#).
- The second style is traditional for Unix and C programmers and is the personal preference of Bjarne Stroustrup.

4.1. When Braces are Needed

All if, while, for and do..while statements must either have braces or be on a single line. This helps to make sure someone adding a line of code does not forget to add braces.

5. Whitespace

Always layout your source code so that elements that are part of a group go together.
Use a blank line to separate groups of code lines.

5.1. No Tab Characters

Do not have any tab characters in your source code. It is difficult to impossible to read source code if your tab settings are different than the authors.

You can make certain that you have converted all your tabs to spaces using Artistic Style (astyle). If Artistic Style is installed on your system, you can use it by typing at the command prompt:

astyle myfile.c

For more information see the astyle manpage or type at the command prompt:

astyle -h

The easy way to remove tabs is to set your text editor to substitute the correct number of spaces for a tab character.

5.2. Line Length

Limit your line length to less than 80 characters since longer lines may cause problems with many text editors and other tools.

5.3. Spacing Around Operators

Always put spaces before and after binary operators. This improves the readability of expressions. For example:

int c = -a * b - d;

5.4. Indentation

Always indent within curly braces. Use 3 or 4 spaces for each indentation level, but be consistent. For example:

void func() 
{
if (something happened)
{
if (another thing happened)
{
while (more input)
{
...
}
}
}
}

5.5. if-else-if-else Formatting

Always line up if statements with their associated else statement. Beyond that, there are two common styles that you may use:

  1. Place brace under and inline with keywords. For example:
    if (condition) // Comment
    {
    ...
    }
    else if (condition) // Comment
    {
    ...
    }
    else // Comment
    {
    ...
    }
  2. Place the initial brace on the same line as the keyword and the trailing brace inline on the same line as the next statement. For example:
    if (condition) { // Comment
    ...
    } else if (condition) { // Comment
    ...
    } else { // Comment
    ...
    }

6. No Magic Numbers

A magic number is a numeric literal that is not defined as a constant. It's magic because no one has a clue what it means after 3 months, including the author. From widespread use, -1, 0, 1, and 2 are not considered magic numbers.

Whenever you assign a number to a variable, use a constant instead. You declare constants, which are variables that cannot change, using the keyword const. You may use local constants within functions, member constants declared in a class, or global constants declared outside of any class or function.

const int MY_CONSTANT = 10;

Because of their special meaning, write constants in all upper case and use underbars ('_') as separators.

Note that in the special case of constant used in array delarations, C++ and C99 severely constrain the use of constants defined with the "const" keyword. In this case you may have to define constants with a preprocessor instruction:

#define ARRAY_SIZE = 10;

The use of const is preferred in all other cases.

7. No Global Variables

A global variable is declared outside of any function and can be accessed by any function in a program. For example, in the following code myGlobal is a global variable.

#include 
using namespace std;
double myGlobal = 0;
int main(void)
{
// main function code
myGlobal = 1;
}

void anotherFunc()
{
myGlobal = 2;
}
// other functions

There is rarely a need to use global variables. Global variables make a program harder to understand and to maintain. Thus, for this course, do NOT use global variables.

Note that global constants do not suffer from the same issues as global variables and they may therefore be used.

Last Updated: 02 April 2010