Page:
CodingStyle
No results
9
CodingStyle
uosfz edited this page 2025-03-12 21:15:56 +01:00
Table of Contents
Coding Style
- indentation: 4 spaces.
- don't align assignments/types over consecutive lines. Exception: preprocessor defines or enum values.
// NO!
int i = 5;
double d = 5.0;
// NO!
int i = 5;
double d = 5.0;
// YES!
int i = 5;
double d = 5.0;
///YES!
#define SHORT_CONSTANT 5
#define VERY_LONG_CONSTANT 6
- do not put short statements in the same line (except empty blocks).
// NO!
if (not_good) return;
// NO!
case 5: return "five";
// NO!
if (la57) { levels = 5; }
- always use braces.
// NO!
for (;;)
do_something();
// YES!
for (;;) {
do_something();
}
- on line break, break before the operator (this does not apply to commas in function calls).
// NO!
bool b = long_val_one ||
long_val_two;
// YES!
bool b = long_val_one
|| long_val_two;
// YES!
func(a,
b);
- in multi-line macros, align escaped newlines.
- always declare enum variants and struct members on their own line.
// NO!
enum values { A, B };
// YES!
enum values {
A,
B
};
- an opening brace starts in the same line, not the next one. Exception: multiline
ifandfor
// NO!
int f()
{
}
// NO!
if (...)
{
}
// NO!
if (a < 3
&& b < 4) {
do_something();
}
// YES!
int f() {
}
// YES!
if (...) {
}
// YES!
if (a < 3
&& b < 4)
{
do_something();
}
- prefer indenting to mulitples of 4 instead of indenting to fit parentheses/operators
// NO!
long_func_call(a,
b);
// NO!
for (int i = 0;
i < 10;
i++)
// NO!
bool b = a
| b;
// NO!
bool b = a
| b;
// YES!
long_func_call(a,
b);
// YES!
long_func_call(
a, b);
// YES!
for (int i = 0;
i < 10;
i++)
// YES!
bool b = a
| b;
- horizontal spacing:
// NO!
if(...){
f ( a, b, c );
}
// YES!
if (...) {
f(a, b, c);
}
caselabels are on the same indentation level as the correspondingswitchstatement.gotolabels and preprocessor directives are never indented.- break after an
__attribute__. - pointers are right-aligned.
// NO!
int* i;
// YES!
int *i;
- leave a blank line between functions/structs/enums.