缩进风格

Indentation style

本文只记录“是什么”,不讨论“好”“坏”。

In computer programming, indentation style is a convention, a.k.a. style, governing the indentation of blocks of source code that is generally intended to convey structure.

Generally, an indentation style uses the same width of whitespace (indentation size) before each line of a group of code so that they appear to be related.

As whitespace consists of both space and tab characters, a programmer can choose which to use - often entering them via the space key or tab key on the keyboard.

K&R

The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently.

K&R
1
2
3
4
while (x == y) {
foo();
bar();
}
1
2
3
4
5
6
7
8
9
10
11
12
int main(int argc, char *argv[])
{
while (x == y) {
do_something();
do_something_else();
if (some_error)
fix_issue(); // single-statement block without braces
else
continue_as_usual();
}
final_thing();
}

One True Brace / 1TBS / OTBS

One True Brace
1
2
3
4
5
6
7
bool is_negative(x) {
if (x < 0) {
return true;
} else {
return false;
}
}

Linux kernel

Linux kernel
1
2
3
4
5
6
7
8
9
10
11
12
int power(int x, int y)
{
int result;
if (y < 0) {
result = 0;
} else {
result = 1;
while (y-- > 0)
result *= x;
}
return result;
}

Stroustrup

Stroustrup
1
2
3
4
5
6
7
8
if (x < 0) {
puts("Negative");
negative(x);
}
else {
puts("Non-negative");
nonnegative(x);
}
Stroustrup
1
2
3
4
5
6
7
8
9
10
11
12
class Vector {
public:
// construct a Vector
Vector(int s) :elem(new double[s]), sz(s) { }
// element access: subscripting
double& operator[](int i) { return elem[i]; }
private:
// pointer to the elements
double * elem;
// number of elements
int sz;
};

Allman

Allman
1
2
3
4
5
while (x == y)
{
foo();
bar();
}

GNU

GNU
1
2
3
4
5
while (x == y)
{
foo();
bar();
}

Whitesmiths

Whitesmiths
1
2
3
4
5
while (x == y)
{
foo();
bar();
}

Ratliff

Ratliff
1
2
3
4
while (x == y) {
foo();
bar();
}

Horstmann

Horstmann
1
2
3
4
while (x == y)
{ foo();
bar();
}

Pico

Pico
1
2
3
while (x == y)
{ foo();
bar(); }

Lisp

Lisp
1
2
3
while (x == y)
{ foo();
bar(); }

APL

APL
1
2
#define W(c,b) {while(c){b}}
W(x==y,s();se();)

Python

Python
1
2
3
while x == y:
foo()
bar()