Changes between Version 3 and Version 4 of CppCodingStandards

Jul 21, 2009, 4:11:44 PM (11 years ago)

began the process of adding in detailed specs...


  • CppCodingStandards

    v3 v4  
    11= C++ Coding Standards =
    34== Overview ==
    56Below I will describes in Gory detail suggested guidelines for C++ code.  These rules apply to new code: new files, new modules, new projects.
    7 When editing an older file to fix a minor bug, etc, I think it's prudent to make small changes to the source. In this case, it will be best for readability if you use the standard that was there previously.  Than includes following the established indentation, placement of curly brackets "{}", naming conventions, etc.
     8When editing an older file to fix a minor bug, etc, I think it's prudent to make as small a change as possible to the source. In this case, it will be best for readability if you use the standard that was there previously.  Than includes following the established indentation, placement of curly brackets "{}", naming conventions, etc.
    910Obviously if the code requires a complete rewrite, then use the suggested coding standards listed below.
    11 Here are some resources and books I like for learning C++, coding standards, and general conventions for C++.  As of this writing (July 2009) C++ is scheduled for a major revision (, and I imagine many new books will come out and make some of my original suggestions obsolete:
     12Here are some resources, and books that I like for learning about C++, coding standards, and general conventions for C++.  As of this writing (July 2009) C++ is scheduled for a major revision (, and I imagine many new books will come out and make some of my original suggestions obsolete:
    1314== Resources ==
    1920Coding Standards
    20   * Used as the main source for those listed below:
     21  * Used as a resource for coding standards listed below:
    2122  * Looks useful as a secondary source:
    2324== Good Books ==
     26There are many, and what you like depends on your learning style.  Here are some of my favorites.
    2528__Intermediate and Advanced__
    4750== Proposed Standard ==
     52As mentioned above, some of this was borrowed from,, with permission as outlined here: "Using this Standard - If you want to make a local copy of this standard and use it as your own you are perfectly free to do so. That's why I made it! If you find any errors or make any improvements please let me know at"  See also and
     54However, as this is a new gamma standard, if you have any immediate issues, send an email to or whoever is managing this standard.
     56=== Introduction ===
     58Standardization is Important. It helps if the standard annoys everyone in some way, so that all members of the team feel they are on the same playing field.
     60==== Good Things about a Standard ====
     62When a project tries to adhere to common standards a few good things happen:
     63  * Programmers can go into any code and figure out what's going on.
     64  * New people can get up to speed quickly.
     65  * People new to C++ are spared the need to develop a personal style and defend it to the death.
     66  * People new to C++ are spared making the same mistakes over and over again.
     67  * People make fewer mistakes in consistent environments.
     68  * Programmers have a common enemy - yes, the standard.
     70==== Bad Points about Having a Standard ====
     72Now the bad:
     73  * The standard is usually stupid because it was "obviously made by someone who doesn't understand C++".
     74  * The standard is usually stupid because it's "not what I do".
     75  * Standards reduce creativity.
     76  * Standards are unnecessary as long as people are consistent.
     77  * Standards enforce too much structure.
     78  * Why bother, people ignore standards anyway.
     79  * Standards can be used as a reason for NIH syndrome(not invented here), because the new/borrowed code won't follow the standard.
     81=== NAMES - General Discussion ===
     83''Using appropriate names for the purpose at hand.''
     85'''Good names are the heart of clear programming!!'''
     87In ancient times people believed that knowing someone's ''true'' name gave them magical power over that person. If you can think up the true name for something, you can give yourself, and the people who read your code, power over the domain.
     89A name is the result of a long deep thought process (or should be) about the ecology it which it lives. Only a programmer who understands the system as a whole can create a name that "fits" with the system.
     91If the name is appropriate everything fits together naturally, relationships are clear, meaning is derived and derivable, and reasoning from common human expectations works as is desired.
     93If you find that all your names look like ''Thing'' and ''Do_It'', then you should probably revisit your design.
     95==== Class Names ====
     97  * Name the class after what it is. If you can't think of what it is, then that's a clue you have not thought through the design well enough. Avoid vague and generic names unless the concept is really vague and generic, which should only be true for abstract classes.  i.e. a Typewriter should be called a Typewriter and not a PushKeyInputSystem.
     98  * Compound names of over three words are a clue that your design may be confusing various entities in your system. Revisit your design. Consider trying a CRC card session to see if your objects have more responsibilities than they should.
     99  * Try to avoid the temptation of bringing the name of the parent class into the derived class's name. A class should stand on its own. It doesn't matter what it derives from.  Only possible exceptions would be abstact class names, like "GroundTransport" (e.g. ChevyMalibu derives from GeneralMotorsCars derives from Automobile derives from GroundTransport derives from Transport... remember it's just an example!).  Of course if you're doing this, you better have a good reason to justify the added complexity of all the abstract classes!
     100  * Suffixes are sometimes helpful. For example, if your system uses agents, then naming an object DownloadAgent conveys real information.
     103==== Method and Function Names ====
     105  * Usually every method and function performs an action, so the name should make clear what it does: CheckForErrors() instead of ErrorCheck(), DumpDataToFile() instead of DataFile(). This will also make functions and data objects more distinguishable.
     106Classes are often nouns. By making function names verbs and following other naming conventions programs can be read more naturally.
     108  * Suffixes are sometimes useful:
     109    * Max - to mean the maximum value something can have.
     110    * Cnt - the current count of a running count variable.
     111    * Key - key value
     112    * (For example: RetryMax to mean the maximum number of retries, RetryCnt to mean the current retry count.)
     114  * Prefixes are sometimes useful:
     115    * Is - to ask a question about something. Whenever someone sees Is they will know it's a question.
     116    * Get - get a value.
     117    * Set - set a value.
     118    * (For example: IsHitRetryLimit, or GetValueCnt.)
     121==== Include Units in Names when Appropriate ====
     122If a variable represents time, weight, or some other unit then include the unit in the name so developers can more easily spot problems, and also know what values to use as input.
     124For example:
     126uint32 m_TimeoutMsecs;
     127uint32 m_MyWeightLbs;
     130Better yet, is to make a variable into a class so bad conversions can be caught. (:Example:?)
     133===== No All Upper Case Abbreviations ====
     135  * When confronted with a situation where you could use an all upper case abbreviation, don't.  Instead use an initial upper case letter followed by all lower case letters.
     139  * People seem to have very different intuitions, when making names containing abbreviations. It's best to settle on one strategy so the names are absolutely predictable.
     141Take for example NetworkABCKey. Notice how the C from ABC and K from key can be confused. Some people don't mind this, and others just hate it, so you'll find different policies in different code and then you never know what to call something.
     145   class FluidOz             // NOT FluidOZ
     146   class NetworkAbcKey       // NOT NetworkABCKey
     150''':Continue Editing Here: - DCT'''
     153=== Names - In Detail ===
     155==== Class Names ====
     156•       Use upper case letters as word separators, lower case for the rest of a word
     157•       First character in a name is upper case
     158•       No underbars ('_')
     160•       Of all the different naming strategies many people found this one the best compromise.
     162   class NameOneTwo
     164   class Name
     167==== Class Library Names ====
     168•       Now that name spaces are becoming more widely implemented, name spaces should be used to prevent class name conflicts among libraries from different vendors and groups.
     169•       When not using name spaces, it's common to prevent class name clashes by prefixing class names with a unique string. Two characters is sufficient, but a longer length is fine.
     171John Johnson's complete data structure library could use JJ as a prefix, so classes would be:
     173   class JjLinkList
     174   {
     175   }
     178=== Method Names ===
     179•       Use the same rule as for class names.
     181•       Of all the different naming strategies many people found this one the best compromise.
     183   class NameOneTwo
     184   {
     185   public:
     186      int                   DoIt();
     187      void                  HandleError();
     188   }
     191==== Class Attribute Names ====
     192•       Attribute names should be prepended with the character 'm'.
     193•       After the 'm' use the same rules as for class names.
     194•       'm' always precedes other name modifiers like 'p' for pointer.
     196•       Prepending 'm' prevents any conflict with method names. Often your methods and attribute names will be similar, especially for accessors.
     198   class NameOneTwo
     199   {
     200   public:
     201      int                   VarAbc();
     202      int                   ErrorNumber();
     203   private:
     204      int                   m_VarAbc;
     205      int                   m_ErrorNumber;
     206      String*               m_pName;
     207   }
     209The original spec had mTimoutMsecs, but I think that m_TimeoutMsecs is more clear as the m is separated from the "TimeoutMsecs".  My only reservation is that it's harder to type, but usually worth the extra effort.
     212==== Method Argument Names ====
     213•       The first character should be lower case.
     214•       All word beginnings after the first letter should be upper case as with class names.
     216•       You can always tell which variables are passed in variables.
     217•       You can use names similar to class names without conflicting with class names.
     219   class NameOneTwo
     220   {
     221   public:
     222      int  StartYourEngines(Engine& rSomeEngine,
     223                            Engine& rAnotherEngine);
     224   }
     227==== Variable Names on the Stack ====
     229i.e. Automatic variables.
     231•       use all lower case letters
     232•       use '_' as the word separator.
     234•       With this approach the scope of the variable is clear in the code.
     235•       Now all variables look different and are identifiable in the code.
     237   int
     238   NameOneTwo::HandleError(int errorNumber)
     239   {
     240      int            error= OsErr();
     241      Time           time_of_error;
     242      ErrorProcessor error_processor;
     243      Time*          p_out_of_time= 0;
     244   }
     246The standard pointer notation is not entirely satisfactory because it doesn't look quite right, but it is consistent.
     248How do you handle statics? There's never a reason to have a static local to a function so there's no reason to invent a syntax for it. But like for most absolute rules, there is an exception, that is when making singletons. Use a "s_" prefix in this case. Take a look at Singleton Pattern for more details.
     251==== Pointer Variables ====
     252•       pointers should be prepended by a 'p' in most cases
     253•       place the * close to the pointer type not the variable name
     256•       The idea is that the difference between a pointer, object, and a reference to an object is important for understanding the code, especially in C++ where -> can be overloaded, and casting and copy semantics are important.
     258•       Pointers really are a change of type so the * belongs near the type. One reservation with this policy relates to declaring multiple variables with the same type on the same line. In C++ the pointer modifier only applies to the closest variable, not all of them, which can be very confusing, especially for newbies. You want to have one declaration per line anyway so you can document each variable.
     261  String* pName= new String;
     263  String* pName, name, address; // note, only pName is a pointer.
     266==== Reference Variables and Functions Returning References ====
     267•       References should be prepended with 'r'.
     269•       The difference between variable types is clarified.
     270•       It establishes the difference between a method returning a modifiable object and the same method name returning a non-modifiable object.
     272   class Test
     273   {
     274   public:
     275      void               DoSomething(StatusInfo& rStatus);
     277      StatusInfo&        rStatus();
     278      const StatusInfo&  Status() const;
     280   private:
     281      StatusInfo&        mrStatus;
     282   }
     285==== Global Variables ====
     286•       Global variables should be prepended with a 'g'.
     288•       It's important to know the scope of a variable.
     290    Logger  gLog;
     291    Logger* gpLog;
     294==== Global Constants ====
     295•       Global constants should be all caps with '_' separators.
     297It's tradition for global constants to named this way. You must be careful to not conflict with other global #defines and enum labels.
     299    const int A_GLOBAL_CONSTANT= 5;
     302==== Static Variables ====
     303•       Static variables may be prepended with 's'.
     305•       It's important to know the scope of a variable.
     307   class Test
     308   {
     309   public:
     310   private:
     311      static StatusInfo msStatus;
     312   }
     315==== Type Names ====
     316•       When possible for types based on native types make a typedef.
     317•       Typedef names should use the same naming policy as for a class with the word Type appended.
     319•       Of all the different naming strategies many people found this one the best compromise.
     320•       Types are things so should use upper case letters. Type is appended to make it clear this is not a class.
     322   typedef uint16  ModuleType;
     323   typedef uint32  SystemType;
     326==== Enum Names ====
     327Labels All Upper Case with '_' Word Separators
     328This is the standard rule for enum labels.
     330   enum PinStateType
     331   {
     332      PIN_OFF,
     333      PIN_ON
     334   };
     336==== Enums as Constants without Class Scoping ====
     337Sometimes people use enums as constants. When an enum is not embedded in a class, make sure you use some sort of differentiating name before the label so as to prevent name clashes.
     339   enum PinStateType            If PIN was not prepended a conflict
     340   {                            would occur as OFF and ON are probably
     341      PIN_OFF,                  already defined.
     342      PIN_ON
     343   };
     345==== Enums with Class Scoping ====
     347Just name the enum items what you wish and always qualify with the class name: Aclass::PIN_OFF.
     348Make a Label for an Error State
     349It's often useful to be able to say an enum is not in any of its valid states. Make a label for an uninitialized or error state. Make it the first label if possible.
     353==== #define and Macro Names ====
     354•       Put #defines and macros in all upper using '_' separators.
     356This makes it very clear that the value is not alterable and in the case of macros, makes it clear that you are using a construct that requires care.
     357Some subtle errors can occur when macro names and enum labels use the same name.
     359#define MAX(a,b) blah
     360#define IS_ERR(err) blah
     363==== C Function Names ====
     364•       In a C++ project there should be very few C functions.
     365•       For C functions use the GNU convention of all lower case letters with '_' as the word delimiter.
     367•       It makes C functions very different from any C++ related names.
     369   int
     370   some_bloody_function()
     371   {
     372   }
     375==== C++ File Extensions ====
     376In short: Use the .h extension for header files and .cc for source files.
     377For some reason an odd split occurred in early C++ compilers around what C++ source files should be called. C header files always use the .h and C source files always use the .c extension. What should we use for C++?
     379The short answer is as long as everyone on your project agrees it doesn't really matter. The build environment should be able to invoke the right compiler for any extension.
     381Historically speaking here have been the options:
     382•       Header Files: .h, .hh, .hpp
     383•       Source Files: .C, .cpp, .cc
     385==== Header File Extension Discussion ====
     386Using .hh extension is not widely popular but makes a certain kind of sense. C header files use .h file extension and C++ based header files use .hh file extension. The problem is if we consider a header file an interface to a service then we can have a C interface to a service and C++ interface to the service in the same file. Using preprocessor directives this is possible and common. The recommendation is to stick with using the .h extension.
     388==== Source File Extension Discussion ====
     389The problem with the .C extension is that it is indistinguishable from the .c extensions in operating systems that aren't case sensitive. Yes, this is a UNIX vs. windows issue. Since it is a simple step aiding portability we won't use the .C extension. The .cpp extension is a little wordy. So the .cc extension wins by default.