Comment types bold comment block comment short single-line comment
C/C++ Programming Style Guidelines
Fred Richards
Before code can be considered for peer review the author must check that it adheres to these guidelines. This may be considered a prerequisite for the review process. A checklist is provided at the end of this document to aid in validating the source code’s style. Where code fails to adhere to the conventions prescribed here may be considered a defect during the review process.
If you have not already, please study Code Complete by Steve McConnell. This book provides a detailed discussion on all things related to building software systems. It also includes references to statistical studies on many of the stylistic elements that affect program maintainability. Another valuable source of solid programming practice tips is The Practice of Programming by Brian W. Kernighan and Rob Pike. Scott Meyers’
2. File Contents
Use files to group functionality. Each file should contain only one cohesive set of functions. Avoid duplicating functionality in separate files. If different files contain similar functions, consider generalizing the function sufficiently and putting it into its own file so that both function groups can use the one source. For C++ code, put only one class or closely related set of classes in each file.
2
C/C++ Style Guide
/*
* Copyright (c) 1999 Fred C. Richards.* All rights reserved.
#ifndef STATISTICS_H
#define STATISTICS_H#include <math.h>
#include <values.h>/*
* Compute the average of a given set.* Input - array of real values, array length. * Output - average, 0 for empty array.
4
C/C++ Style Guide
3. Preprocessor directives, #include and #define
4. Revision-string variable
static const char rcs_id[] __attribute__ ((unused)) = "$Id$";
The __attribute__ modifier is a GNU C feature that keeps the compiler from complaining about the unused variable. This may be omitted for non-GNU projects.
C/C++ Style Guide
Example 2. Standard (C++) implementation/code file
#include "Class.h"
#include <string>namespace {
const char rcs_id[] = "$Id$";
}^L
...
6
(add-hook ’c-mode-common-hook ’my-c-mode-common-hook)
Format your code so that the spatial structure illustrates the logical structure. Use blank lines to help separate different ideas, use indentation to show logical relationships, and use spaces to separate functionality. Each block of code should do exactly one thing.
.
.
Use four spaces for each level of indentation. Avoid making lines longer than 80 characters. When breaking lines, use the natural logical breaks to determine where the newline goes. Indent the continuation line to illustrate its logical relationship to the rest of the code in the line. For functions, for example, this means aligning arguments with the opening parenthesis of the argument list.
Example 4. Breaking statements across multiple lines
if (value < max) {
if (value != 0) {
func(value);
}
8
Start public, protected, private, and friend labels in column zero of class declarations. Use explicit public labels for all struct public fields and use explicit private labels for all private class members.
The members of a class should be declared in the following order. Declare all public data members and type definitions first. Declare private or protected data members or type definitions used in function member initialization lists or inline implementations next. Declare all public member functions next, starting with the constructors and destructor. Declare all remaining private or protected data members and type definitions next. Declare all private or protected function members next. Declare all friends last.
C/C++ Style Guide
int get_x() const { return x_; }
void set_x(const int new_x) { x_ = new_x; } ...
The name formatting conventions described here are essentially the GNU coding standards. These are available online using info.
Use lower case for all variable names. For multi-word names, use an underscore as the separator. Use all capitals for the names of constants (i.e. variables declared const and enumerated types). Use an underscore as a word separator.
C/C++ Style Guide
• Avoid names that are homophones: e.g., foo, fu, phoo, etc. Also, don’t rely on capitalization to distinguish between variables.
4.2. Function Names
Use lower-case letters for public function names. Use an underscore as a word separator.
11
C/C++ Style Guide
*/
float
gain(void);In general, be consistent and be informative. Choose names that make your code easy to read and understand.
12
C/C++ Style Guide
class Canvas {
public:
enum Pen_style {
NONE = 0,
PENCIL,
BRUSH,
BUCKET
};Canvas();
~Canvas();
int cached_y_;
// C++ usage example
Canvas sketch_pad;
sketch_pad.set_pen_style(Canvas::BRUSH);
// Notice how redundant "stack" becomes.
template <Type>
class Stack {
public:
int stack_size;
add_item_to_stack(Type item);
...
In general, well written code should document itself. Clear, concise variable and function names, consistent formatting and spatial structure, and clean syntactical structure all contribute to readable code. Occasionally, however, complex logic will benefit from explicit description. Be careful not to use comments to compensate for poorly written code. If you find that your code requires many comments or is often difficult to describe, perhaps you should be rewriting the code to make it simpler and clearer.
14
Too few or too many comments is an indicator of code that is likely to be difficult to maintain.
Avoid the use of end-line comments except for variable declarations and for marking #if/#endif statements. Make comments be the only thing on a line. For longer comments describing more complex logic, use a block style to offset them from the code better. Use block-style comments to describe functions. Use bold comments to delimit major sections of your code file. Preface all bold comments and block
comments that introduce functions with a form-feed character so that they appear at the start of the printed page. The following example shows the various comment types in the C style.*/
/* Short (single-line) comment. */
End-line comments are acceptable for describing variable declarations. Use a comment to describe any variable whose purpose is not obvious from its name.
Use comments to document your intent. Do not describe how your code works, that should be obvious from the implementation. Instead describe why your code does what it does. Avoid explaining especially tricky code in comments. Instead, rewrite the code to make it intrinsically more obvious. Use complete sentences with proper spelling and punctuation in all comments.
Example 10. Commenting functions and function groups
^L
/*
* Compute the standard deviation or "variance" * for a set.*
* Input: v - set of values and set size.Use an end-line comment also to identify which #if or #ifdef statement a particular #endif statement closes. Include the condition in the comment for blocks of code spanning more than a few lines. When using #else conditions, mark both the #else and the #endif statements with the negated condition (i.e. preface it with “not”).
Example 11. Commenting long code blocks
#else // not DEBUG
void
function()
{if (position != END)
#endif // not DEBUG
6. Syntax and Language Issues
Avoid putting multiple instructions on the same line. Each line should do exactly one thing. This is applies in particular to control statements for branch and loop structures.
Consider the following:
/* Safer version */
if (!eof) {
count = get_more();
if (count > min_required) {
...
19
C/C++ Style Guide
Use parentheses to group logic in branch and loop control structures. Most people are not intimately familiar with operator precedence, and parentheses can make logic operations much easier for people to parse and understand. Without the additional parentheses it is not obvious that the first case below differs from the other three (which are equivalent) for only one of the eight combinations of the booleans x, y and z:
Example 12. One of these things is not like the other
20