This is my personal C++ code style guide.
General
Example Code
#include <iostream>
namespace foo::bar {
template<typename T>
class baz {
public:
baz();
~baz();
u32 private_member() const;
void private_member(u32 new_value) noexcept;
T public_member;
private:
u32 _private_member;
};
int main(i32 argc, char** argv) {
if (argc > 1) {
return 1;
}
baz<f32> my_baz;
std::cout << "Hello, World!" << std::endl;
return 0;
}
}
Naming Conventions
- All code and comments should use U.K. English spelling and grammar
- All names are
snake_case
, the only exception are constants, which are inkCamelCase
. - Private members use leading underscore, like
_private_member
- Classes that are abstract interfaces are named like
Iclass_name
.
Formatting
Indentation uses spaces. The size of one tab is 2 spaces.
Braces are placed on the same line as the statement, like
if (expression) {
}
The preffered line limit is between 80 and 100 characters.
Pointers and references shall be declared like T& x
Portable C++ code
bool
for boolean values.char
for characters.iN (intN_t)
anduN (uintN_t)
for signed and unsigned integers types with bit size ofN
.f32 (float)
for single precision floating point (4 bytes).f64 (double)
for double precision floating point (8 bytes).
Use of C++ STL standard library
The use of C++ STL types is encouraged and preferred. The C++ STL should be preferred over C standard library functions.
Comments
You should write self-documenting code if possible. But comments are allowed.
C++ Style comments (// comment ... ... ... ...
) are preffered.
Files
- File name shall be treated as case sensitive.
- File names shall be lower case, shall not contain spaces and shall use underscores as word seperator.
- C source files shall have the extension
.c
. - C header files shall have the extension
.h
. - C++ source files shall have the extension
.cc
. - C++ header files shall have the extension
.hh
. - Header files must have include guards. The use of
#pragma once
is preferred. - Public headers shall be included with
<>
, private headers shall be included with""
. - Put include directives at the top of files.
Statements
- Use gotos only if they have a big performance benefit.
- All switch statements shall have a default label, even if all values are covered by case labels. If all values are covered by case labels an assert shall be placed in the default label.
Semantics
Use plenty of assertions.
Always validate function input.
nullptr
nullptr
should be used instead of the C-style NULL
macro in all cases.