22
Feb
0

C++ – Style Guide, Advices & Tips

A few months ago I developed several applications in C++. So, I create a small style guidelines and I list some optimizations useful to develop good programs.

Comments

There are based on DOxygen syntax. You can find more resources at :

www.doxygen.org

http://www.digilife.be/quickreferences/QRC/Doxygen%20Quick%20Reference.pdf

Functions

- optional : @fn {prototype}
@brief {short description}
@author {author}

- optional : @example …

Classes

- optional : @class {class name} or @interface
@author {author(s)}
@version {version}
@date {date}
- optional : @file {file name}
@package {package name}
@brief {short description}

- optional : @example

Example :

/**
 * @file main.c
 * @brief My tests.
 *         more brief description
 * @author Franck.H
 * @version 0.1
 * @date September 6 2007
 *
 * This class uses a string to connect to a DB.
 *
 */

Methods

-optional : @fn {prototype}
@brief {short description}
@author {author}
@param <name> { description }
@return { description of the returned value }
@warning {warning}

Example :

/**
 * @fn static Str_t * str_new (const char * sz)
 * @brief Create a new Str_t object.
 *         and increment a value
 *
 * @param sz Array where to store Str_t, cannot be NULL.
 * @return New array Str_t or NULL in case of error
 *
 * This function can be used like this or that
 * etc
 *
 */

Attributes

Use /**< */ on the right of the attribute

Example :


int EVal1; /**< enum value 1 */

List

If you need to write a list in your comment use :

/**
* @li at the beginning of the lines
* or html tags :
* <ol>
*  <li>
* </ol>
*/

Mathematics

You can write an equation like :

/**
* \f$ \sqrt{(x-x_0)^2-(y-y_0)^2} \f$ (it will generate a pretty draw)
* x^{2}
* \frac{x}{y}
* \sum_{k=1}^n
* \pi
* x_{0}
* \sqrt[n]{x}
* \int_{a}^b dt
* \Pi
*/

Complexity

If needed, use :

/**
* @complexity O(n)
*/

Syntax – The minimum

Several element in the syntax are felt differently by every one. For example, I like to put { in the same line of the prototype, but you may prefer to write it the line after.
So, I give a very light style guide with the minimum rules.

Static

Every static things start with an Upper Char :
void StaticMethod();
int StaticAttribute;

Classes

If possible one class per file (with the same name).
The class name must starts with a upper letter.
Please give it the following constructor :

  • default constructor (no parameters)
  • copy constructor
  • copy operator
  • destructor
  • and all the constructors you need :)

All methods (especially for getter/setter) with less than 5 lines must be in the hpp (to be inlined).

Protection

Use protected or private depending if you would like to be inherited.

Variables

Local variable [localVariable] : words in lower letters with a upper letter at the beginning of words
parameter [inParameterFunction] : in_ or in at the beginning
attribute [_attribute] : _ at the biginning

index (indexArray or iteratorList) : put information in the name (like indexCities etc.) not just i or j!

Tips & Optimization

Loops

Use pre-inc (++index) and not post-inc (index++).

Do not create temporaries objects, for example with iterator if you do like :
for(Iter index = list.begin() ; index != list.end() ; ++index)
you will create temporary object each loop (with list.end() that returns an iterator).
So do like :
Iter end = list.end();
for(Iter index = list.begin() ; index != end ; ++index)

We can put “return” directly in the loop, it is faster than “break”.

Parameters

Use references for objects and value for basic types (int, float, etc).
Use const every where you can.
If you need to modify an object use pointer.

Test

We do not test with true/false/equal etc, so do not write : if( variable == true )
but : if( variable )

Do not test equality between decimal variables (like double/float)
You cannot do double1 == double2 with floating value!
You have to use something like :
abs(double1 – double2) < FLT_EPSILON

Declaring variables

Declare variables by group of type (the int together, the char together etc.)
Declare variables when you have something to put into.

Switch or if else

With more than 3 if… if else … if else … if you can use a switch or organize the tests.

Use iterative

If possible use iterative and not recursive.

Comparing Array

If you need to compare two array/string compare the first value before creating a loop.

Cout

std::endl put a ‘\n’ and flush the stream. So use ‘\n’ and sometime use std::endl

Modulus

For int value you can do : myInt % modInt =>> myInt & (modInt-1)

With integer value if you need to do %2, please test the last bit
myInt % 2 =>> myInt & 0×01

Clone

When you duplicate an object copy values with memcpy and copy array/object etc…

Oject *o = new Object();
memcpy(o, inObject , sizeof(Object));
o.anObject = inObject;

Not null but 0

Use 0 (not 0×00) to replace C Null
const int NULL = 0;

Use C++ more than C Macro

const TYPE
enum
are better than define

typedef

Use typedef for changing type

int & double

Use int and double more than short/long/float etc.

Be careful when convert signed & unsigned

Do not use implicit cast between signed and unsigned value

Use C++ cast more than C old-style cast

static_cast : example int to short , or pointer to another pointer etc.
reinterpret : example int to pointer
dynamic_cast : for runtime cast
const_cast : for un-const/const only

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.

Comments are closed.

Celadon theme by the Themes Boutique