C++ Programming Style Guidelines
Version 4.5, April 2007
Geotechnical Software Services
Copyright © 1996 - 2007
This document is available at http://geosoft.no/development/cppstyle.html
Table of Content
- 1 Introduction
- 2 General Recommendations
- 3 Naming Conventions
- 4 Files
- 5 Statements
- 6 Layout and Comments
- 7 References
This document lists C++ coding recommendations common in the C++ development community.
The recommendations are based on established standards collected from a number of sources, individual experience, local requirements/needs, as well as suggestions given in [1] - [4].
There are several reasons for introducing a new guideline rather than just referring to the ones above. Main reason is that these guides are far too general in their scope and that more specific rules (especially naming rules) need to be established. Also, the present guide has an annotated form that makes it far easier to use during project code reviews than most other existing guidelines. In addition, programming recommendations generally tend to mix style issues with language technical issues in a somewhat confusing manner. The present document does not contain any C++ technical recommendations at all, but focuses mainly on programming style. For guidelines on C++ programming style refer to the C++ Programming Practice Guidelines.
While a given development environment (IDE) can improve the readability of code by access visibility, color coding, automatic formatting and so on, the programmer should never rely on such features. Source code should always be considered larger than the IDE it is developed within and should be written in a way that maximize its readability independent of any IDE.
1.1 Layout of the Recommendations.
The recommendations are grouped by topic and each recommendation is numbered to make it easier to refer to during reviews.
Layout of the recommendations is as follows:
n. Guideline short description |
Example if applicable |
Motivation, background and additional information. |
The motivation section is important. Coding standards and guidelines tend to start "religious wars", and it is important to state the background for the recommendation.
In the guideline sections the terms must, should and can have special meaning. A must requirement must be followed, a should is a strong recommendation, and a can is a general guideline.
1. Any violation to the guide is allowed if it enhances readability. |
|
The main goal of the recommendation is to improve readability and thereby the understanding and the maintainability and general quality of the code. It is impossible to cover all the specific cases in a general guide and the programmer should be flexible. |
2. The rules can be violated if there are strong personal objections against them. |
|
The attempt is to make a guideline, not to force a particular coding style onto individuals. Experienced programmers normally want adopt a style like this anyway, but having one, and at least requiring everyone to get familiar with it, usually makes people start thinking about programming style and evaluate their own habits in this area. On the other hand, new and inexperienced programmers normally use a style guide as a convenience of getting into the programming jargon more easily. |
3.1 General Naming Conventions
3. Names representing types must be in mixed case starting with upper case. |
Line, SavingsAccount |
Common practice in the C++ development community. |
4. Variable names must be in mixed case starting with lower case. |
line, savingsAccount |
Common practice in the C++ development community. Makes variables easy to distinguish from types, and effectively resolves potential naming collision as in the declaration Line line; |
5. Named constants (including enumeration values) must be all uppercase using underscore to separate words. |
MAX_ITERATIONS, COLOR_RED, PI |
Common practice in the C++ development community. In general, the use of such constants should be minimized. In many cases implementing the value as a method is a better choice: int getMaxIterations() // NOT: MAX_ITERATIONS = 25 { return 25; } This form is both easier to read, and it ensures a unified interface towards class values. |
6. Names representing methods or functions must be verbs and written in mixed case starting with lower case. |
getName(), computeTotalWidth() |
Common practice in the C++ development community. This is identical to variable names, but functions in C++ are already distingushable from variables by their specific form. |
7. Names representing namespaces should be all lowercase. |
model::analyzer, io::iomanager, common::math::geometry |
Common practice in the C++ development community. |
8. Names representing template types should be a single uppercase letter. |
template<class T> ... template<class C, class D> ... |
Common practice in the C++ development community. This makes template names stand out relative to all other names used. |
9. Abbreviations and acronyms must not be uppercase when used as name [4]. |
exportHtmlSource(); // NOT: exportHTMLSource(); openDvdPlayer(); // NOT: openDVDPlayer(); |
Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type whould have to be named dVD, hTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readbility is seriously reduced; the word following the abbreviation does not stand out as it should. |
10. Global variables should always be referred to using the :: operator. |
::mainWindow.open(), ::applicationContext.getName() |
In general, the use of global variables should be avoided. Consider using singleton objects instead. |
11. Private class variables should have underscore suffix. |
class SomeClass { private: int length_; } |
Apart from its name and its type, the scope of a variable is its most important feature. Indicating class scope by using underscore makes it easy to distinguish class variables from local scratch variables. This is important because class variables are considered to have higher significance than method variables, and should be treated with special care by the programmer. A side effect of the underscore naming convention is that it nicely resolves the problem of finding reasonable variable names for setter methods and constructors: void setDepth (int depth) { depth_ = depth; } An issue is whether the underscore should be added as a prefix or as a suffix. Both practices are commonly used, but the latter is recommended because it seem to best preserve the readability of the name. It should be noted that scope identification in variables has been a controversial issue for quite some time. It seems, though, that this practice now is gaining acceptance and that it is becoming more and more common as a convention in the professional development community. |
12. Generic variables should have the same name as their type. |
void setTopic(Topic* topic) // NOT: void setTopic(Topic* value) // NOT: void setTopic(Topic* aTopic) // NOT: void setTopic(Topic* t) void connect(Database* database) // NOT: void connect(Database* db) // NOT: void connect (Database* oracleDB) |
Reduce complexity by reducing the number of terms and names used. Also makes it easy to deduce the type given a variable name only. If for some reason this convention doesn't seem to fit it is a strong indication that the type name is badly chosen. Non-generic variables have a role. These variables can often be named by combining role and type: Point startingPoint, centerPoint; Name loginName; |
13. All names should be written in English. |
fileName; // NOT: filNavn |
English is the prefered language for international development. |
14. Variables with a large scope should have long names, variables with a small scope can have short names [1]. |
|
Scratch variables used for temporary storage or indices are best kept short. A programmer reading such variables should be able to assume that its value is not used outside a few lines of code. Common scratch variables for integers are i, j, k, m, n and for characters c and d. |
15. The name of the object is implicit, and should be avoided in a method name. |
line.getLength(); // NOT: line.getLineLength(); |
The latter seems natural in the class declaration, but proves superfluous in use, as shown in the example. |
3.2 Specific Naming Conventions
17. The terms get/set must be used where an attribute is accessed directly. |
employee.getName(); employee.setName(name); matrix.getElement(2, 4); matrix.setElement(2, 4, value); |
Common practice in the C++ development community. In Java this convention has become more or less standard. |
18. The term compute can be used in methods where something is computed. |
valueSet->computeAverage(); matrix->computeInverse() |
Give the reader the immediate clue that this is a potential time consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability. |
19. The term find can be used in methods where something is looked up. |
vertex.findNearestVertex(); matrix.findMinElement(); |
Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability. |
20. The term initialize can be used where an object or a concept is established. |
printer.initializeFontSet(); |
The american initialize should be preferred over the English initialise. Abbreviation init should be avoided. |
21. Variables representing GUI components should be suffixed by the component type name. |
mainWindow, propertiesDialog, widthScale, loginText, leftScrollbar, mainForm, fileMenu, minLabel, exitButton, yesToggle etc. |
Enhances readability since the name gives the user an immediate clue of the type of the variable and thereby the objects resources. |
22. Plural form should be used on names representing a collection of objects. |
vector<Point> points; int values[]; |
Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements. |
23. The prefix n should be used for variables representing a number of objects. |
nPoints, nLines |
The notation is taken from mathematics where it is an established convention for indicating a number of objects. |
24.The suffix No should be used for variables representing an entity number. |
tableNo, employeeNo |
The notation is taken from mathematics where it is an established convention for indicating an entity number. An elegant alternative is to prefix such variables with an i: iTable, iEmployee. This effectively makes them named iterators. |
25. Iterator variables should be called i, j, k etc. |
for (int i = 0; i < nTables); i++) { : } for (vector<MyClass>::iterator i = list.begin(); i != list.end(); i++) { Element element = *i; ... } |
The notation is taken from mathematics where it is an established convention for indicating iterators. Variables named j, k etc. should be used for nested loops only. |
26. The prefix is should be used for boolean variables and methods. |
isSet, isVisible, isFinished, isFound, isOpen |
Common practice in the C++ development community and partially enforced in Java. Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to choose more meaningful names. There are a few alternatives to the is prefix that fits better in some situations. These are the has, can and should prefixes: bool hasLicense(); bool canEvaluate(); bool shouldSort(); |
27. Complement names must be used for complement operations [1]. |
get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume, etc. |
Reduce complexity by symmetry. |
28. Abbreviations in names should be avoided. |
computeAverage(); // NOT: compAvg(); |
There are two types of words to consider. First are the common words listed in a language dictionary. These must never be abbreviated. Never write: cmd instead of command Then there are domain specific phrases that are more naturally known through their abbreviations/acronym. These phrases should be kept abbreviated. Never write: HypertextMarkupLanguage instead of html |
29. Naming pointers specifically should be avoided. |
Line* line; // NOT: Line* pLine; // NOT: LIne* linePtr; |
Many variables in a C/C++ environment are pointers, so a convention like this is almost impossible to follow. Also objects in C++ are often oblique types where the specific implementation should be ignored by the programmer. Only when the actual type of an object is of special significance, the name should empahsize the type. |
30. Negated boolean variable names must be avoided. |
bool isError; // NOT: isNoError bool isFound; // NOT: isNotFound |
The problem arises when such a name is used in conjunction with the logical negation operator as this results in a double negative. It is not immediately apparent what !isNotFound means. |
31. Enumeration constants can be prefixed by a common type name. |
enum Color { COLOR_RED, COLOR_GREEN, COLOR_BLUE }; |
This gives additional information of where the declaration can be found, which constants belongs together, and what concept the constants represent. An alternative approach is to always refer to the constants through their common type: Color::RED, Airline::AIR_FRANCE etc. |
32. Exception classes should be suffixed with Exception. |
class AccessException { : } |
Exception classes are really not part of the main design of the program, and naming them like this makes them stand out relative to the other classes. |
33. Functions (methods returning something) should be named after what they return and procedures (void methods) after what they do. |
|
Increase readability. Makes it clear what the unit should do and especially all the things it is not supposed to do. This again makes it easier to keep the code clean of side effects. |