Some C++ coding tips:
- Do not turn off warning level(s) from compilation. This will save you trouble later. Use as much stricter settings as possible.
- Do not ignore warning(s) in your build process.
- Stick to ANSI C++ coding as much as possible.
All header file code must be contained within:
#ifndef __file_h
#define __file_h 1
… (code)
#endif
Use “#pragma once” as first line of header file if using Visual C++ compiler 2003 and later.
- Do not use “goto” if possible.
- Always perform clean build before code submission and/or merge.
- Use “const” modifier as much as possible.
- Define “enum” with assigned values. Do not let it go for assumption. This improves readability. Say,
enum MyEnum {
SUNDAY = 0,
MONDAY = 1,
}; // enum for days
- Use brackets in pre-processor director. Say,
#define BIT(n) (1 << n) // not preferred
#define BIT(n) (1 << (n)) // preferred
- Prefer library functions that take size or count argument over to functions without such argument for string manipulation. Say,
strncpy is preferred over strcpy.
- One include file should not contain more than one class definitions.
- Using “const” or “enum” is preferred over using “define” for contants. Say,
#define LOOP_COUNT 100 // non preferred
const int LOOP_COUNT = 100; // preferred
enum { LOOP_COUNT = 100, }; // or preferred
- A member function that does not modify class state must be declared as “const”.
- A class must have a default constructor with all data members initialized in it.
- A class must have copy constructor and assignment operator defined to avoid surprises.
- Assignment operator function must take care of destructive operation e.g. assigning to self (a = a).
- Avoid functions having more than five arguments.
- Do not mix malloc/free and new/delete.
- If array is allocated using “new”, use “delete []” for deallocating it.
- Avoid type conversions if possible.
- Re-initialize pointer when deallocated. Say,
delete p;
p = NULL;
- It is good to have a carriage return in the end of a code file.
- Use inclusive lower limit and exclusive upper limit in “for” loop. Say,
for ( int idx = 0; idx < MAX; ++idx ) // exclusive upper limit
for ( int idx = MAX; idx >= 1; –idx ) // inclusive lower limit
- Do not use “static” variable in “inline” function in header file.
I hope that this article is helpful and will avoid some silly bugs creeping over your code :-)
August 16, 2008 at 3:19 am
Oh, Thanks! Really amazing. Big ups!