C++ Coding Standards

The following is not intended to generate a holy war, but merely a place for me to remind myself of the decisions I took along the way to get to a consistent style for any new code that I write.

IDE

Tabs set to 4, and set it to replace all tabs with spaces. Shift-Tab will backspace a tabs worth of spaces. Using spaces is so the code will look the same when cut and paste into other environments, like these blogs, email, and also online code links to godbolt.org

Compiler

-Wall and then turn off using pragma for any that are not needed.

Use C++ 11 for a simpler life and good compatibility. I am unlikely to use any of the new features. OK so there are a few nice features. I will list them here and if they grow useful enough the default could be moved to C++ 17.

Update: So using structs for partial template specialisation is a nice clean way to do it, but there is a lot of extra code to get to a series of key inline functions that do the special part that is needed depending on the template parameters.. It also make the code harder to write. First you write the code as you would and then remove the core differences into these inline functions. I also found that many cases these are not in critical performance paths so having the extra branch would not be a problem on C++11. So I am moving over to setting C++17 by default from here on in.

  • constexpr if statement
  • Default Template Definition with out <> – Class template argument deduction

if constexpr

This allows for compile time inclusion of code. This is like replacing the preprocessor and having macros.

inline static member variable for a class

This is much more convienant than having to put the declaration in the class and then the static assignment at the end, outside of the class.

inline static const char* emptyConstString = "";

Class template argument deduction (CTAD)

This allows for a class like cString<allocator=heap> and then call it without the template brackets.

enum allocator::source { heap, stack };
// ...
template<int source = allocator::source::heap>
// ...
cString<> usingDefaultAlloc;
cString<allocator::source::stack> fasterAlloc;
// and replace it with
cString usingDefaultAlloc;
cString<allocator::source::stack> fasterAlloc;

However note that it is easier to create specific names for them. Use nameClass for the main class and then the default can be just name

using name= nameClass;

Braces

Allman style with forced braces even for one line. Collapsing code into one neat little line is very tempting, but key reasons not to is for code readability and allowing for a place to step inside the debugger. Vertical space is not that critical if the code is clear and, simple and broken down to low Cyclomatic Complexity. I keep trying and can never get on with K&R style and its variants.

There is an exception so as to prove the above being true.

For code using if constexpr() where it is a one liner selection, that can be without the braces.

if constexpr_(isStack)
    newBlock = alloca(_poolBlockSize);
else
    newBlock = malloc(_poolBlockSize);

Identifiers

Take your pick from: camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE.

My preference is camelCase as that is easier to type the snake_case, but the later feels more C++. Modern C++ have moved away from SCREAMING_SNAKE_CASE and I think that is a good move.

I tried snake_case for a while and the underscore is not that much of an issue because of the autocomplete. I still feel that camelCase is more readable and natural. It also takes up less space on a line.

camelCase it is then.

Hungarian or English?

I grew up with strong Hungarian notation and it makes sense in C where the typing is very weak. For modern C++ there is a view that this is not necessary any more as the compiler will warn of any conversions. That leaves member variable and static/global variables. While the m_ approach is nice, if you do that, then why not for everything.

My solution was arrived at by realising the member and static variables are to some degree special and that this can follow the direction indicated by the reserved cases for identifiers (__example, _ANOTHER). Thus, while using underscore is frowned upon, I like the notation to show the intent that these things are ‘part of inner code’. The same approach is to be used for static variables in the class or struct scope and also for local functions that clash with standard library versions.

class entity
{
    static constexpr size_t     _maxEntities = 1000;
    entity(char* name)
    {
        _name = name;
    };
    char    _name[8];
};

inline float _floor(const float& a);

For true global variable, use a single global struct call ‘g’. This allows for a central way to create a warning that these values must be written to very carefully.

struct globals
{
    int     count = 0;
    bool    isGameRunning = false;
}
struct globals g;
...
g.count++;    // Not thread safe.

camelCase can also be used for filenames. This is in contradiction to keeping all filenames lowercase to help with any accidental file use under windows due to case-insensitivity. But for consistency sake and a nice look it will be used here as well.

hashTable.h
imageScaler.h
vectorTests.cpp

Naming Conventions

size_t  n;          // For bytes in a buffer
int     i;          // For loops etc only
size_t  index;      // For array index - don't use 'i'
size_t  length;     // For char* only
size_t  size;       // For number of items in classes
size_t  capacity;   // For current max number of items
type    rhs;        // For operators overloads with lhs and rhs

Use nullptr over NULL to get the type information for the compiler.

Alignment

alignas
alignof
size_of

Align classes and structures to 8 bytes unless they only contain char. This is because all compiles will be 64bit.

If using SSEM then align to 16 bytes and make sure the class or struct is a multiple of 16 using packing.

Project Include Files

I am generating a set of one file includes for various core functionality. EG, Vectors, Intrinsics, Maths, Lists, HashTable, Allocator etc. these are to be used in any project I work on and I have been temporarily using:

#include    "../include/maths.h"

Which is just terrible. The reason is that I am using Visual Studio IDE and I don’t really want to have any changes from the default configuration of the IDE. However I am starting to build up a list of critical things that are needed. So from here on in I will just list them in an IDE set up post and then I add things as needed.

Comments from Various Sources

I’m a contract videogame programmer, so the answer is: I follow whatever the company guidelines call for. Typically, videogame code doesn’t use RTTI or exceptions, and follow CamelCase naming rules, m_ member variables, s_ static variables, and tab=4s. It’s remarkably consistent across the industry, for some reason. BoarsLair

I learned about how Plan 9 C code had non-traditional scheme of #include files where they don’t put #ifdef wrappers in each .h file to allow multiple inclusion and .h files don’t include other .h files. As a result .c files have to include every .h file they need and in the right order. It’s a bit of a pain and no other modern C++ codebase I know of maintains such discipline. But it’s my project so I did it and I keep doing it. It prevents circular dependencies between .h files and doesn’t inflate C++ build times because of careless including the same files over and over again. Chris/Krzysztof Kowalczyk