C++ Code Guidelines
Under Construction
This section of the documentation is not formalized and may change.
Help us by contributing to it on our GitHub.
Help us by contributing to it on our GitHub.
Names
Use pascal case for structs and snake case for variables and functions.
tip
When defining a const variable always write it in UPPERCASE
Do ✅:
struct Example;
size_t example_t;
void example_func();
int example_var;
const EXAMPLE_VAR;
Don't ❌:
struct example;
size_t exampleT; // size_t exampleSize;
void ExampleFunc(); // void exampleFUNC();
int exampleVar;
const example_var;
Use full words, except when the variable name is too long.
Do ✅:
int my_var;
int length;
char width;
Don't ❌:
int my_variable;
int len;
char width;
caution
When declaring a constant use always CONST and not PREPROCESSOR DIRECTIVES
Use descriptive names in functions.
Do ✅:
char convert_to_ascii(int);
Don't ❌:
char to_ascii(int);
Leave useless variable names out of function declarations.
Do ✅:
char my_character(char);
Don't ❌:
char my_character(char character);
Switch
In switch cases don't indent another level.
tip
Same thing for classes!
Do ✅:
switch (foo) {
case 1:
printf("bread");
case 2:
printf("akane");
default:
printf("akane cat");
}
Don't ❌:
switch (foo) {
case 1:
printf("bread");
case 2:
printf("akane");
default:
printf("akane cat");
}
Headers
Use #pragma once
for header files. Why? Because #pragma once
is less prone to making mistakes and it is less code to type.
Do ✅:
#pragma once
Don't ❌:
#ifndef FILE_H
#define FILE_H
/*
* code
*/
#endif // FILE_H
Include libraries first, then include local headers.
Do ✅:
#include <stdio.h>
#include "file.h"
Don't ❌:
#include "file.h"
#include <stdio.h>
Blocks
When writing a function, or a for cycle, don't write curly braces at the beginning of a new line.
Do ✅:
int my_function(int a, int b) {
// code
}
for (int i = 0; i <= 10; i++) {
printf("%d\n", i);
}
Don't ❌:
int my_function(int a, int b)
{
// code
}
for (int i = 0; i <= 10; i++)
{
printf("%d\n", i);
}
Use 4 spaces as tab instead of 2.
Do ✅:
int my_function(int a, int b) {
// code
if (my_statement == true)
{
// code
}
else
{
return 1;
}
}
Don't ❌:
int my_function(int a, int b) {
// code
if (my_statement == true)
{
// code
}
else
{
return 1;
}
}
Statements
Use conditional operators instead of if else statements.
Do ✅:
my_variable % 2 == 0 ? printf("even") : printf("odd");
Don't ❌:
if (my_variable % 2 == 0) {
printf("even");
} else {
printf("odd");
}
When the statement is too long, go to a new line.
Do ✅:
my_variable % 2 == 0 && my_variable2 % 4 == 0 ? printf("foo") : \
my_variable3 % 6 == 0 && my_variable4 % 8 == 0 ? printf("fee") : printf("fuu");
Don't ❌:
my_variable % 2 == 0 && my_variable2 % 4 == 0 ? printf("foo") : my_variable3 % 6 == 0 && my_variable4 % 8 == 0 ? printf("fee") : printf("fuu");
Types
Delete int
when using an unsigned
modifier, and don't use a signed
modifier.
Do ✅:
unsigned my_variable;
int my_variable2;
Don't ❌:
unsigned int a;
signed b;
signed int c;