C++ coding style

c++, coding-style

Solution

There are many coding standards available by respected institutions:

Here is a good one https://wiki.ucar.edu/download/attachments/25039241/european_space_agency_standards.pdf

Problem

not sure if my question suits all rules for StackOverflow question, but I think it will be helpful for future users. Now I need to choose coding style for a few C++ projects where I'm participating. These projects are big enough and there will be a few programmers working on every. So we need to equalize our code style. Also we want to choose coding style which is socially acceptable, so first I'll tell what we already decided to have. My question is, if some of our choices is not socially unaccepted and also what are others commonly using C++ coding style rules. So here what we chosen: File naming Start with a capital letter and have a capital letter for each new word (no underscores, no spaces). For example: ``` VeryImportantClass.h VeryImportantClass.cpp ``` Namespace naming Start with a capital letter and have a capital letter for each new word (no underscores, no spaces). Also alignment should be appropriate. For example: ``` namespace Drinks { namespace AlcoholDrinks { } } ``` Namespace structure In header file the have only functions/methods prototypes, realization in `cpp` file, avoid using `using namespace` for realization file. Example: ``` //header namespace CommonStuff { namespace SystemParameters { bool IfWindows(); //some more stuff... } } //cpp file namespace CommonStuff { namespace SystemParameters { bool IfWindows() { //some stuff... return ...; } } } ``` Classes and structures naming Start with a capital letter and have a capital letter for each new word (no underscores, no spaces). No C like class prefix or S like struct prefix. We decided - it is just more typing. Example: ``` class MyClass { }; struct MyStruct { }; ``` class or struct In some cases it is difficult to understand if we need class or struct. If structure just keep some grouped data - it is `struct`. If structure keeps data and has methods - it is `class`. Exceptional methods are constructor, destructor and comparison operators. Example: ``` class MyClass { public: MyClass(); ~MyClass(); void SetValue(int value); int GetValue(); void PrintValue(); private: int m_value; }; struct MyStruct { MyStruct(); ~MyStruct(); int value; }; ``` Type names Start with a capital letter and have a capital letter for each new word (no underscores). For example: ``` typedef std::string String; typedef std::vector<String> StringVector; ``` Variable types Use our own predefined types, we have: ``` typedef std::string String; typedef std::vector<String> StringVector; typedef unsigned char Byte; typedef std::vector<Byte> ByteVector; //etc. ``` Variable naming Start with a lower letter and have a capital letter for each new word (no underscores). Example: ``` String messageLicenseExpired = "Your product version is expired, please..."; int importantNumber = 13; ``` Class variables naming Starts with prefix m_ then word starts with a lower letter and have a capital letter for each new word (no underscores). Example: ``` int m_myVariable; int m_otherVariable; ``` Constants Use all capitals with underscores. Example: ``` const String PRODUCT_NAME = "our product"; const Byte IMPORTANT_NUMBER = 13; ``` Constants or preprocessor If value will be checked using `#ifdef` or some others, then it must be preprocessor definition. Otherwise it is `const`. For example: ``` #define FAILURE_FACTOR_FOR_DEBUG 50 const int MAGIC_NUMBER = 5; //some code... String newString = someString.substr(MAGIC_NUMBER); //some code... //not the best example, but I think it is understandable. #ifdef _DEBUG int someValue = FAILURE_FACTOR_FOR_DEBUG; #else int someValue = 0; #end ``` Function and methods naming Start with a capital letter and have a capital letter for each new word (no underscores). For example: ``` int CalculateSometing (int n); void ToUpper (String& someStr); ``` Braces Braces should always go into new line, except initializing. Example: ``` int arr[] = {1, 2, 3}; if (arr[0] > 10) { //do something } else { //do something else } ``` else `else` belongs to new line, see previous example. if statement and braces Even single code line after `if` or `else` should be enclosed. Example: ``` if (someInt > 100) { someInt = 100; } else { someInt /= 2; } ``` Methods calling No space around arrow and dot. Example: ``` Object obj; Object* oPtr = new Object(); obj.Method(); obj->Method(); ``` Header files - use `#pragma once` in stead of define guards. (`#pragma once` is not standart so in some compilers define guards are must) - One header for one class only. - Header files only for definitions. Execution instructions must be in related `cpp` file even if it getter or setter. It is because changes in header leads into long compiling. Pointers and references Use reference instead of pointer if it is possible. If possible pass parameter as a reference (for objects), prefer to pass as a `const` reference if value will not be changed. Example: ``` String ToUpper(String str); //bad String ToUpper(String& str); //better String ToUpper(const String& str); //best void ToUpper(String& str); //also solution ``` Error handling If function may fail, it must return `bool` value `true` for success and `false` for failure. For classes method `GetLastError()` is a must. For function that may fail error code should be returned through additional parameter, e.g. `bool Function(int param, int* errorCode = NULL)` Also we decided not to use exceptions in our code. class structure In header file first public methods (constructors and destructors at the top of them), protected methods, protected variables, private methods, private variables. No public variables, use getters and setters. Example: ``` class MyClass { public: MyClass(); ~MyClass(); int GetPrivateValue(); void SetPrivateValue(int value); int GetProtectedValue(); void SetProtectedValue(int value); protected: void SomeMethod(); int m_protectedValue; private: void SomePrivateMethod(); int m_privateValue; }; ``` Formatting - Alignment use 4 spaces or tab. - Long line wrapping, no longer lines then 120 symbols. Self documenting code Comments are always welcome but the best choice is to give name for variables and functions which explains everything. Example: ``` void Function (const String& str, const String& str2, StringVector& vect); //very bad //This functions tokenize string, str is input string, str2 is delimiters string, vect output void Function (const String& str, const String& str2, StringVector& vect); //quite bad void Tokenize (const String& inputString, const String& delimiters, StringVector& output); //good, anyway comments using this declaration also welcome. ``` & and * position Write `&` and `*` just after variable type. Example: ``` String* strPtr; String& strRef; ``` It is all we decided to use, the question is, haven't we missed something? Also, is there anything globally unacceptable? Feel free to comment and ask if something is not clear, why we chosen some. Hope it will be helpful for latter readers.

Original source