Style rules for writing C++

These are the standards used to evaluate the code students submit for projects and on written assignments and tests. Students in my classes are required to follow them.

Syntax and indenting

  1. Do not use tabs. Ever. You can eliminate tabs from your code by using a good text editor (e.g. VIM, Notepad++, Emacs, etc.) and configuring it to insert spaces instead of tabs. In VIM, this is done with ":set et". Any good text editor will let you find existing tabs by searching for "\t" (without quotes).
  2. Use a 4-space indent.
  3. Use proper indentation for every block of code.
  4. Keep lines of code short. Optimally 80 characters, but no more than 100.
  5. Opening braces appear on the same line as the preceding statement (i.e. function opening, if, for, while, case, etc.).

Code use

  1. Use meaningful but concise variable names.
  2. All variables must be properly initialized.
  3. Global variables are not allowed; global constants are allowed.
  4. Constants use only upper-case letters and underscores (e.g. SOME_CONSTANT). Variables do not use this naming scheme. A constant's name should not reference its own value. For example, here are some terrible constant names:
    const int INDEX_TWO = 2;
    const int TOKEN_4 = 4;
    Again, names should convey meaning, not value.
  5. "Magic numbers" are not allowed. A magic number is a literal (constant value, e.g. 34) which has a special meaning, but the meaning is only known to the programmer. Instead, use constants with appropriate names. Usually, +1, 0, and -1 are not magic numbers. Here is an example of a magic number:
    int err = open_a_file(filename);
    if (err == 18) {
        // do something
    }
    
    Here is the same code with the magic number given a name so its meaning is clear:
    const int ERROR_FILE_DOESNT_EXIST = 18;
    // ...
    int err = open_a_file(filename);
    if (err == ERROR_FILE_DOESNT_EXIST) {
        // do something
    }
    
  6. Do not #include .cpp files in any other file.
  7. Do not test "this" for NULL. A program should never call a method on a NULL pointer in the first place, so testing "this" for NULL is a sign of bad design.
  8. Passing parameters:
    1. Use pass by const reference for any large object that will not be modified by a function. Large here means "not a simple C++ type". A simple C++ type is something like a bool or an int or a double.
    2. Use pass by pointer for any object that will be modified by a function. By using pass by pointer only in this context, it helps distinguish the fact that the passed-in object is expected to be modified by the function.
    3. Use pass by value for any small object (e.g. int, etc.) that will not be modified by a function.

Writing and comments

  1. Use correct spelling, complete sentences, and proper grammar.
  2. Use comments liberally, but wisely.
  3. Use in-line comments (starting with //) within a function to explain complex/unclear sections of code.
  4. Don't write comments about things that are obvious from reading the code, such as "add one to i," or "returns an int." Comments should enlighten the reader and give meaning to the code.
  5. Each function must have a comment block before it, which gives the function name, describes each parameter and the return value (if any), and explains the purpose of the function. Refer to the parameters by name, not by type. Here is an example:
    /**
     * nchoosek
     *
     * This function computes (n choose k), the number of ways to choose a subset
     * of k items from a group of n items, where 0 ≤ k ≤ n. This can be
     * computed in many ways, but here we use the basic factorial definition, which
     * can overflow quite easily. This definition is:
     * 
     *   (n choose k) = n! / ((n-k)! * k!)
     * 
     * Parameters:
     *   n: the number of items in the larger group
     *   k: the size of the subset to choose
     * 
     * Return value: the number of ways to choose k out of n items
     */
    int factorial(int n) {
        if (k < 0 || n < k) {
            return 0;
        }
        return factorial(n) / (factorial(n - k) * factorial(k));
    }

    A comment about a parameter or return value should enlighten the reader about its purpose, not just its type. For example, the following is not a useful comment for the function :

     * Return value: ostream &
    ostream & operator<<(ostream & os, Object const & obj) {
    It's not useful because it doesn't explain why an ostream reference is being returned, and the programmer could probably just look at the function signature to determine this. A more useful comment might be:
     * Return value: the given stream, to permit output chaining
    Here, it's clear that the purpose of returning the ostream is to allow the caller to chain output calls. Finally, when referring to parameters to a method in comments, refer to them by name, not by type.
  6. Each class declaration must have a comment block before it, which gives the class name and describes the purpose of the class. Here is an example:
    /**
     * SinglyLinkedList
     * 
     * This class implements a linked list with single forward links, and supports
     * dynamic addition and deletion of nodes. 
     */
    class SinglyLinkedList {
        public:
            // ...
    };
    
  7. Each file must have a block comment at the top which gives the name of the file, the student's name, the assignment, the date, the version, and a comment about what is contained in the file. For example:
    /**
     * file: SinglyLinkedList.h
     * author: student name
     * course: CSI 3334
     * assignment: project 1
     * due date: August 30, 2003
     * version: 1.3
     * 
     * This file contains the declaration of the SinglyLinkedList abstract data
     * type.
     */
    

Some thoughts on style rules

Some students wonder why different professors have their own style rules, and they all insist on different rules. The point is to get used to different conventions. One way is not necessarily better than another, but if the student learns to be flexible enough use different styles, he/she'll be prepared to adapt to other conventions in the future. Also, the student will be able to establish his/her own ideas about what is best.


Copyright © 2004 Greg Hamerly
Computer Science Department
Baylor University

valid html and css