Vous êtes sur la page 1sur 17

Summary of C++ Coding Guidelines

2015

Summary of C++ Coding Guidelines


Author: Vic P.
Contact: vic4key[at]gmail.com

Purpose
The purpose of this document is to define one style of programming in
C++. The guidelines presented here are not final, but should serve as a basis for
continued work with C++. This collection of guidelines should be seen as a
dynamic document; suggestions for improvements are encouraged.
Programs that are developed according to these guidelines should be:

Correct

Easy to maintain.

In order to reach these goals, the programs should:

Have a consistent style,

Be easy to read and understand,

Be portable to other architectures,

Be free of common types of errors,

Be maintainable by different programmers.


Questions of design, such as how to design a class or a class hierarchy,

are beyond the scope of this document.


Page 1 of 17

Summary of C++ Coding Guidelines

2015

In order to obtain insight into how to effectively deal with the most
difficult aspects of C++, the examples of code that are provided should be
carefully studied. C++ is a difficult language in which there may be a very
fine line between a feature and a bug. This places a large responsibility upon
the programmer. C++ allows a programmer to write compact and, in some
sense, unreadable code.

Page 2 of 17

Summary of C++ Coding Guidelines

2015

Contents
Coding Guidelines for C++ ........................................................................................... 1
Purpose .............................................................................................................................. 1
Source Code In Files............................................................................................... 5
Naming of Files.................................................................................................... 5
Code Structure ..................................................................................................... 5
Include Files ......................................................................................................... 5
Comments ............................................................................................................. 6
Style ........................................................................................................................... 7
General .................................................................................................................. 7
Assigning Names ................................................................................................ 7
o In General ............................................................................................................. 7
o Class names .......................................................................................................... 8
o Variable names .................................................................................................... 8
o Other names ......................................................................................................... 8
o Prefixes .................................................................................................................. 8
o Classes ................................................................................................................... 9
o Functions ............................................................................................................... 9
Classes..................................................................................................................... 10
Access Right ....................................................................................................... 10
Inline Functions ................................................................................................. 10
Friends ................................................................................................................. 10
Const Member Functions ................................................................................. 10
Constructors and Destructors .......................................................................... 10
Assignment Operators ...................................................................................... 11
Operator Overloading....................................................................................... 11
Member Function Return Types..................................................................... 11
Inheritance .......................................................................................................... 11
Class Templates ................................................................................................. 12
Functions ................................................................................................................ 12
General ................................................................................................................ 12
Function Arguments ......................................................................................... 12
Function Overloading ....................................................................................... 13
Formal Arguments............................................................................................. 13
Page 3 of 17

Summary of C++ Coding Guidelines

2015

Return Types and Values ................................................................................. 13


Inline Functions ................................................................................................. 13
Temporary Objects ............................................................................................ 13
Constants ................................................................................................................ 13
Variables................................................................................................................. 14
Floating Point Variables .................................................................................. 14
Containers ........................................................................................................... 14
Pointers and References ................................................................................... 14
Type Conversions ................................................................................................. 14
Flow Control Structures....................................................................................... 14
Expressions ............................................................................................................ 15
Memory Allocation............................................................................................... 15
Fault Handling ...................................................................................................... 16
Portability............................................................................................................... 16
Sizes of Types .................................................................................................... 16
Type Conversions.............................................................................................. 16
Data Representation ......................................................................................... 16
Order of Execution ............................................................................................ 16
Temporary Objects............................................................................................ 17
Pointer Arithmetic ............................................................................................. 17
References ....................................................................................................................... 17

Page 4 of 17

Summary of C++ Coding Guidelines

2015

General
o Every time you deviate from these standards, it must be clearly
documented.
o Optimize the code only if you know that you have a performance
problem. Think twice before you begin.

Source Code In Files


Naming of Files
o Include files should always have the file name extension ".h"
o Implementation files should always have the file name extension ".cpp"
o Inline definition files should always have the file name extension ".inl"
o The include, implementation, and inline definition file (if used) for a
class should have a file name of the form <class name - 'C'> +extension.
Use uppercase and lowercase letters in the same way as in the source
code.
Code Structure
o Source code files are to have the following order:
1. Beginning comment block (see section on commenting).
2. Include statements.
3. Define statements.
4. Local data type definitions.
5. Static function prototypes
6. Static data.
7. Externally visible functions.
8. Local functions.
Include Files
Page 5 of 17

Summary of C++ Coding Guidelines

2015

o The include file should contain all declarations for classes, structures,
and functions.
o An include file should never contain more than one class definition.
o Every include file should have a guard block (such as the "#pragma
once" compiler directive) to prevent multiple inclusion.
o An Include file should contain as few #include directives as possible.
o When using the #include directive, use "file.h" for user-prepared include
files, and <file.h> for library include files.
Comments
o Implementation comments.
Should be compact and easy to find.
Should not duplicate information that is easy to see by looking at the
code.
Should be minimized by choosing proper names for classes, functions
and variables and by properly structuring code.
o Documentation comments.
Every file must contain a beginning comment block that contains the
file's name, author, and a Copyright notice.
All classes must contain a descriptive comment block immediately
before their definition in the header file.
All public members of a class must contain a descriptive
comment block before their definition in the include file.
For public functions this must include descriptions of inputs, outputs
and return values.
Page 6 of 17

Summary of C++ Coding Guidelines

2015

Style
General
o Do not use spaces around '.' or '->', nor between unary operators and
operands.
o Indent each nested code block.
o Braces ("{}") that enclose a block are to be placed in the same column, on
separate lines directly before and after the block.
o The flow control primitives if, else, while, for and do should be followed
by a block, even if it is an empty block.
o Only one variable should be declared per line.
o The dereference operator '*' and the address-of operator '&' should be
directly connected with the type names in declarations and definitions.
Assigning Names
o In General
A name should denote meaning so other developers

may easily

understand the purpose of the object in question.


A name that cannot be pronounced is a bad name.
A long name is normally better than a short, cryptic name, but avoid
overly long names, as these become tedious with repetition.
Do not use names that begin with anything other than alpha
characters.
Do not use names that are ambiguous in meaning.
Names should not include abbreviations that are not generally
accepted.
Page 7 of 17

Summary of C++ Coding Guidelines

2015

Separate words in a name either through capitalization or using


underscores ('_').
o Class names
Are to begin with a capital letter 'C'.
The first letter of each word in a class name should be uppercase,
with the rest of the letters lowercase.
Classes should be named so that "object.function" is easy to read and
appears to be logical.
Template class names are to end with a capital letter 'T', for example
CArrayT.
o Variable names
Class member variables shall begin with a prefix of 'm_'. The first
letter of each word in the member variable name should be
uppercase, with the rest of the letters lowercase.
Variable names of pointers should begin with a lowercase 'p'.

For

class member variables, this results in the prefix 'm_p'.


Short names, such as i, j and k are acceptable for loop counters.
The names of constants should be in all uppercase with words
separated by '_'.
o Other names
The names of abstract data types, structures, typedefs, and
enumerated types are to begin with an uppercase letter.
Do not use typenames that differ only by the use of uppercase and
lowercase letters.
o Prefixes
Page 8 of 17

Summary of C++ Coding Guidelines

2015

A short, descriptive prefix, followed by an underscore, should be


used for the following:
Type names (typedefs, enums, structs, unions, etc.)
Global variables, constants, and functions.
Preprocessor macros (#define)
o Classes
The public, protected, and private sections of a class are to be
declared in the following order:
1. public
2. protected
3. private
No member functions are to be defined within the class definition.
o Functions
Always provide the return type of a function explicitly.
Function declarations:
Shall appear with the leading parenthesis and the first argument
(if any) on the same line as the function name.
If space permits, other arguments and the closing parenthesis may
also be written on the same line as the function name.
Otherwise, each additional argument is to be written on a separate
line.
The closing parenthesis shall appear directly after the last
argument.
Always write the left parenthesis directly after a function name.
Page 9 of 17

Summary of C++ Coding Guidelines

2015

Classes
Access Right
o Member data in a class should always be private.
o Structs should not be used as they contain only public data.
Inline Functions
o Access and Forwarding functions should be defined inline.
o Constructors and destructors must never be defined inline.
Friends
o Friends of a class should be used to provide additional functions that are
best kept outside of the class.
o Friends are good if used properly. However, the use of many friends
can indicate that the modularity of the system is poor.
Const Member Functions
o A member function that does not affect the state of an object (its instance
variables) is to be declared const.
o If the behavior of an object is dependent on data outside the object, this
data is not to be modified by const member functions.
o Avoid explicit type conversions from a const type to a non-const type.
Constructors and Destructors
o A class that uses "new" to allocate instances managed by the class,
must define a copy constructor.
o All classes that are used as base classes and that have virtual functions,
must define a virtual destructor.
o Avoid the use of global objects in constructors and destructors.
Page 10 of 17

Summary of C++ Coding Guidelines

2015

o Do not call virtual function in a constructor.


Assignment Operators
o A class that uses "new" to allocate instances managed by the class, must
define an assignment operator.
o If an assignment operator is overloaded, the programmer must make
certain that the base class' and the members' assignment operators are
run.
o An assignment operator that performs a destructive action must be
protected from performing this action on the object upon which it is
operating.
o An assignment operator ought to return a const reference to the
assigning object.
Operator Overloading
o Use operator overloading sparingly and in a uniform manner. Do not
use it if it can easily give rise to misunderstanding.
o Never, ever overload the unary operator '&'. (The address-of operator).
o When two operators are opposites (such as == and !=), always define
both.
Member Function Return Types
o A public member function must never return a non-const reference or
pointer to member data.
o A public member function must never return a non-const reference or
pointer to data outside an object, unless the object shares the data with
other objects.
Inheritance
Page 11 of 17

Summary of C++ Coding Guidelines

2015

o Avoid inheritance for parts-of relations.


o Give derived classes access to class type member data by declaring
protected access functions.
Class Templates
o Do not attempt to create an instance of a class template using a type that
does not define the member functions that the class template, according
to its documentation, requires.
o Take care to avoid multiple definition of overloaded functions in
conjunction with the instantiation of a class template.
Functions
General
o Avoid long and complex functions.
Function Arguments
o Do not use unspecified function arguments (ellipsis notation).
o Function arguments that are passed by pointer or reference should be
declared as const unless:
o Avoid functions with many arguments.
o If a function stores a pointer to an object that is accessed via an
argument, let the argument have the type pointer. Use reference
arguments in other cases.
o A function that changes the value of a pointer that is provided as an
argument, should declare the argument as having the type reference to
pointer (e.g. char*&).
o Use constant references (const &) instead of call-by-value, unless using a
Page 12 of 17

Summary of C++ Coding Guidelines

2015

pre-defined data type or a pointer.


Function Overloading
o When overloading functions, all variations should have the same
semantics (be used for the same purpose).
Formal Arguments
o The names of formal arguments to functions are to be specified and are
to be the same both in the function declaration and in the function
definition.
Return Types and Values
o Always specify the return type of a function explicitly.
o A public function must never return a reference or a pointer to a local
variable.
o Return values for functions that have a large memory footprint should
be passed as a non-const pointer or reference at the end of the parameter
list.
Inline Functions
o Only use inline functions when they are really needed.
o Do not use the preprocessor directive #define to obtain more efficient
code; instead, use inline functions.
Temporary Objects
o Minimize the number of temporary objects that are created as return
values from functions or as arguments to functions.
Constants
o Constants are to be defined using const or enum; never using #define.
Page 13 of 17

Summary of C++ Coding Guidelines

2015

o Avoid the use of numeric values in code; use symbolic values instead.
Variables
o Variables are to be declared with the smallest possible scope.
o Each variable is to be declared in a separate declaration statement.
o Every variable that is declared is to be given a value before it is used.
o If possible, always use initialization instead of assignment.
Floating Point Variables
o Always prefer the floating point type 'double' to that of 'float'.
Containers
o Avoid using C-style arrays for containers. Instead of using a C-style
array use a container class.
Pointers and References
o Pointers to pointers should be avoided whenever possible.
o Use a typedef to simplify program syntax when declaring function
pointers.

Type Conversions
o Avoid using explicit casts where possible.
o Never use C-style explicit type conversions (casts).
o Do not write code that depends on functions that use implicit type
conversions.
o Never convert pointers to objects of a derived class to pointers to objects
of a virtual base class.
o Never convert a const to a non-const.

Flow Control Structures


Page 14 of 17

Summary of C++ Coding Guidelines

2015

o A break statement must always terminate the code following a case


label.
o A switch statement must always contain a default branch that handles
unexpected cases.
o Never use goto.
o The choice of loop construct (for, while or do-while) should depend on
the specific use of the loop.
o Always use unsigned for variables that cannot reasonably have negative
values.
o Always use inclusive lower limits and exclusive upper limits.
o Avoid the use of continue.
o Use break to exit a loop if this avoids the use of flags.
o Do not write logical expressions of the type if(test) or if(!test) when test is
a pointer.
o Consider the scope within which an iteration variable is visible.
Expressions
o Use parentheses to clarify the order of evaluation for operators in
expressions.

Memory Allocation
o Do not use malloc, realloc or free.
o Always provide empty brackets ("[]") for delete when deallocating
arrays.
o Avoid global data if at all possible.
o Do not allocate memory and expect that someone else will deallocate it
Page 15 of 17

Summary of C++ Coding Guidelines

2015

later.
o Always assign a new value to a pointer that points to deallocated
memory.

Fault Handling
o Check the fault codes that may be received from library functions even if
these functions seem.
o foolproof.
Portability
Sizes of Types
o Do not assume that any two types have the same size.
o Do not assume that a char is signed or unsigned.
o Always set char to unsigned if 8-bit ASCII is used.
Type Conversions
o Do not assume that pointers and integers have the same size.
o Use explicit type conversions for arithmetic using signed and unsigned
values.
Data Representation
o Do not assume that you know how an instance of a data type is
represented in memory.
Order of Execution
o Do not assume that the operands in an expression are evaluated in a
definite order.
o Do not assume that you know how the invocation mechanism for a
function is implemented.
Page 16 of 17

Summary of C++ Coding Guidelines

2015

o Do not assume that an object is initialized in any special order in


constructors.
o Do not assume that static objects are initialized in any special order.
Temporary Objects
o Do not write code that is dependent on the lifetime of a temporary
object.
Pointer Arithmetic
o Avoid using shift operations instead of arithmetic operations.
o Avoid pointer arithmetic.

References
[1] Programming in C++, Rules and Recommendations - FN/Mats Henricson and
Erik Nyquist.
[2] Doxygen Manual www.doxygen.org

Page 17 of 17

Vous aimerez peut-être aussi