Indentation style: Difference between revisions
m The core is brace example, but code should still be logical and make sense. Bad form: 1) void return? 2) puts function (side effect) if negative 3) call a separate function (with no idea whether it mutates values). Keeping general form (of bracing) intact, but fixing syntax and semantics that were incompatible approaches. |
→Variant: 1TBS (OTBS): parentheses after `return` are rarely seen in 1TBS (and generally) |
||
Line 160: | Line 160: | ||
bool is_negative(x) { |
bool is_negative(x) { |
||
if (x < 0) { |
if (x < 0) { |
||
return |
return true; |
||
} else { |
} else { |
||
return |
return false; |
||
} |
} |
||
} |
} |
Revision as of 09:17, 22 January 2024
In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be (and often is) applied to most other programming languages (especially those in the curly bracket family), where whitespace is otherwise insignificant. Indentation style is only one aspect of programming style.
Indentation is not a requirement of most programming languages, where it is used as secondary notation. Rather, indenting helps better convey the structure of a program to human readers. Especially, it is used to clarify the link between control flow constructs such as conditions or loops, and code contained within and outside of them. However, some languages (such as Python and occam) use indentation to determine the structure instead of using braces or keywords; this is termed the off-side rule. In such languages, indentation is meaningful to the compiler or interpreter; it is more than only a clarity or style issue.
This article uses the term brackets to refer to parentheses, and the term braces to refer to curly brackets.
Brace placement in compound statements
The main difference between indentation styles lies in the placing of the braces of the compound statement ({...}
) that often follows a control statement (if
, while
, for
...). The table below shows this placement for the style of statements discussed in this article; function declaration style is another case. The style for brace placement in statements may differ from the style for brace placement of a function definition. For consistency, the indentation depth has been kept constant at 4 spaces, regardless of the preferred indentation depth of each style.
Brace placement | Styles |
---|---|
while (x == y)
{
something();
something_else();
}
|
Allman |
while (x == y)
{
something ();
something_else ();
}
|
GNU |
while (x == y)
{
something();
something_else();
}
|
Whitesmiths |
while (x == y) {
something();
something_else();
}
|
K&R |
while (x == y) {
something();
something_else();
}
|
Ratliff |
while (x == y)
{ something();
something_else();
}
|
Horstmann |
while (x == y)
{ something();
something_else(); }
|
Pico |
while (x == y)
{ something();
something_else(); }
|
Lisp |
#define W(c,b) {while(c){b}}
W(x==y,s();se();)
|
APL |
Tabs, spaces, and size of indentations
The displayed width for tabs can be set to arbitrary values in most programming editors, including Notepad++ (MS-Windows), TextEdit (MacOS/X), Emacs (Unix), vi (Unix), and nano (Unix). In addition, these editors can be configured to generate a mix of tabs and spaces or to convert between tabs and spaces, to match specific indentation schemes. In Unix, the tab width can also be set in pagers, such as less, and converted on the fly by filters, such as expand/unexpand.
Unix editors default to positioning tabs at intervals of eight columns, while Macintosh and MS-Windows environments defaulted to four columns. This difference causes source code misalignment, when indentation that mixes tabs and spaces is displayed under a configuration that displays tabs differently from the author's configuration.
There is ongoing debate amongst programmers about the choice between hard tabs and spaces. Many early programmers used tab characters to indent, for ease of typing and to save on source file size. Some programmers, such as Jamie Zawinski, state that using spaces instead of tabs increases cross-platform portability.[1] Others, such as the writers of the WordPress coding standards, state the opposite: that hard tabs increase portability.[2] A survey of the top 400,000 repositories on GitHub found that spaces are more common.[3]
The size of the indentation is usually independent of the style. An experiment performed on PASCAL code in 1983, found that indentation size significantly affected comprehensibility. Indentation sizes between 2 and 4 characters proved optimal.[4] For Ruby, many shell scripting languages, and some forms of HTML formatting, two spaces per indentation level is generally used.[citation needed]
Tools
There are many tools to convert between indentation styles, such as indent
, a program included with many Unix-like operating systems.
In Emacs, various commands are available to automatically fix indentation problems, including hitting Tab
on a given line (in the default configuration). M-x indent-region
can be used to properly indent large sections of code. Depending on the mode, Emacs can also replace leading indentation spaces with the proper number of tabs followed by spaces, which results in the minimal number of characters for indenting each source line.
Elastic tabstops is a tabulation style which requires support from the text editor, where entire blocks of text are kept automatically aligned when the length of one line in the block changes.
Styles
K&R style
The K&R style (Kernighan & Ritchie Style), and the closely related "one true brace style" in hacker jargon[5][6] (abbreviated as 1TBS[7]), are commonly used in C, C++, and other curly-brace programming languages. It was the style used in the original Unix kernel, Kernighan and Ritchie's book The C Programming Language, as well as Kernighan and Plauger's book The Elements of Programming Style.
When following K&R, each function has its opening brace at the next line on the same indentation level as its header, the statements within the braces are indented, and the closing brace at the end is on the same indentation level as the header of the function at a line of its own.
Multi-line blocks inside a function, however, have their opening braces at the same line as their respective control statements; closing braces remain in a line of their own, unless followed by a keyword else
or while
. Such non-aligned braces are nicknamed "Egyptian braces" (or "Egyptian brackets") for their resemblance to arms in some fanciful poses of ancient Egyptians.[8][9][10] In K&R, single-line blocks do not have braces, which is a possible source of easy-to-miss bugs when merging code (for example, see the goto fail bug).
int main(int argc, char *argv[])
{
...
while (x == y) {
something();
something_else();
if (some_error)
do_correct(); // In K&R a single-statement block does not have braces.
else
continue_as_usual();
}
final_thing();
...
}
The C Programming Language does not explicitly specify this style, though it is followed consistently throughout the book. From the book:
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.
In old versions of the C language, argument types needed to be declared on the subsequent line (i.e., just after the header of the function):
/* Original pre-ISO C style without function prototypes */
int main(argc, argv)
int argc;
char *argv[];
{
...
}
Variant: 1TBS (OTBS)
The "one true brace style" (abbreviated as 1TBS or OTBS[7]) is very similar to K&R. The main two differences are that functions have their opening braces on the same line separated by a space, and that the braces are not omitted for a control statement with only a single statement in its scope.[11]
In this style, the constructs that allow insertions of new code lines are on separate lines, and constructs that prohibit insertions are on one line. This principle is amplified by bracing every if, else, while, etc., including single-line conditionals, so that insertion of a new line of code anywhere is always safe (i.e., such an insertion will not make the flow of execution disagree with the source code indenting, as seen for example in Apple's infamous goto fail bug).
Suggested advantages of this style are that the starting brace needs no extra line alone, and the ending brace lines up with the statement it conceptually belongs to. One cost of this style is that the ending brace of a block needs a full line alone, which can be partly resolved in if/else blocks and do/while blocks:
bool is_negative(x) {
if (x < 0) {
return true;
} else {
return false;
}
}
There are many mentions of The One True Brace Style, but there is some confusion as to its true form. Some sources say that it is the variation specified above,[11] while others note that it as just another "hacker jargon" term for K&R.[5]
Variant: Linux kernel
A minor variant of the K&R style is the Linux kernel style, which is known for its extensive use in the source tree of the Linux kernel.[12] Linus Torvalds strongly advises all contributors to follow it. The style borrows many elements from K&R.
The kernel style uses tab stops (with the tab stops set every 8 characters) for indentation. Opening curly braces of a function go to the start of the line following the function header. Any other opening curly braces go on the same line as the corresponding statement, separated by a space. Labels in a switch
statement are aligned with the enclosing block (there is only one level of indents). Line length used to be limited to 80 characters – it was raised to 100 in 2020, but the original limit is still preferred.[13] A single-statement body of a compound statement (such as if, while, and do-while) need not be surrounded by curly braces. If, however, one or more of the substatements in an if-else
statement require braces, then both substatements should be wrapped inside curly braces:
int power(int x, int y)
{
int result;
if (y < 0) {
result = 0;
} else {
result = 1;
while (y-- > 0)
result *= x;
}
return result;
}
Variant: mandatory braces
Some advocate mandatory braces for control statements with only a single statement in its scope, i.e., bracing every if, else, while, etc., including single-line conditionals, so that insertion of a new line of code anywhere is always safe (i.e., such an insertion will not make the flow of execution disagree with the source-code indentation).
The cost of this style is that one extra full line is needed for the last block (except for intermediate blocks in if/else if/else constructs and do/while blocks).
Variant: Java
While Java is sometimes written in other styles, a significant body of Java code uses a minor variant of the K&R style in which the opening brace is on the same line not only for the blocks inside a function, but also for class or method declarations. This style is widespread largely because Sun Microsystems's original style guides[14][15][16] used this K&R variant, and as a result, most of the standard source code for the Java API is written in this style. It is also a popular indentation style for ActionScript and JavaScript, along with the Allman style.
Variant: Stroustrup
Stroustrup style is Bjarne Stroustrup's adaptation of K&R style for C++, as used in his books, such as Programming: Principles and Practice using C++ and The C++ Programming Language.[17]
Unlike the variants above, Stroustrup does not use a "cuddled else". Thus, Stroustrup would write[17]
if (x < 0) {
puts("Negative");
negative(x);
}
else {
puts("Non-negative");
nonnegative(x);
}
Stroustrup extends K&R style for classes, writing them as follows:
class Vector {
public:
Vector(int s) :elem(new double[s]), sz(s) { } // construct a Vector
double& operator[](int i) { return elem[i]; } // element access: subscripting
int size() { return sz; }
private:
double * elem; // pointer to the elements
int sz; // number of elements
};
Stroustrup does not indent the labels public:
and private:
. Also, in this style, while the opening brace of a function starts on a new line, the opening brace of a class is on the same line as the class name.
Stroustrup allows writing short functions all on one line. Stroustrup style is a named indentation style available in the editor Emacs. Stroustrup encourages a K&R-derived style layout with C++ as stated in his modern C++ Core Guidelines.[18]
Variant: BSD KNF
Also termed Kernel Normal Form, this is the form of most of the code used in the Berkeley Software Distribution (BSD) operating systems. Although mostly intended for kernel code, it is also widely used in userland code. It is essentially a thoroughly documented variant of K&R style as used in the Bell Labs Version 6 & 7 Unix source code.[19]
The SunOS kernel and userland uses a similar indentation style.[19] Like KNF, this also was based on AT&T style documents and is sometimes termed Bill Joy Normal Form.[20] The SunOS guideline was published in 1996; ANSI C is discussed briefly. The correctness of the indentation of a list of source files can be verified by the cstyle program written by Bill Shannon.[19][20][21]
In this style, the hard tabulator (ts in vi) is kept at eight columns, while a soft tabulator is often defined as a helper also (sw in vi), and set at four. The hard tabulators are used to indent code blocks, while a soft tabulator (four spaces) of additional indentation is used for all continuing lines that must be split over multiple lines.
Moreover, function calls do not use a space before the parenthesis, although C-language native statements such as if
, while
, do
, switch
and return
do (in the case where return
is used with parens). Functions that declare no local variables in their top-level block should also leave an empty line after their opening block brace.
Here follow a few samples:
while (x == y) {
something();
something_else();
}
final_thing();
if (data != NULL && res > 0) {
if (JS_DefineProperty(cx, o, "data",
STRING_TO_JSVAL(JS_NewStringCopyN(cx, data, res)),
NULL, NULL, JSPROP_ENUMERATE) != 0) {
QUEUE_EXCEPTION("Internal error!");
goto err;
}
PQfreemem(data);
} else {
if (JS_DefineProperty(cx, o, "data", OBJECT_TO_JSVAL(NULL),
NULL, NULL, JSPROP_ENUMERATE) != 0) {
QUEUE_EXCEPTION("Internal error!");
goto err;
}
}
static JSBool
pgresult_constructor(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval)
{
QUEUE_EXCEPTION("PGresult class not user-instantiable");
return (JS_FALSE);
}
Allman style
The Allman style is named after Eric Allman. It is also sometimes termed BSD style since Allman wrote many of the utilities for BSD Unix (although this should not be confused with the different "BSD KNF style"; see above).
This style puts the brace associated with a control statement on the next line, indented to the same level as the control statement. Statements within the braces are indented to the next level.[22]
while (x == y)
{
something();
something_else();
}
final_thing();
This style is similar to the standard indentation used by the Pascal languages and Transact-SQL, where the braces are equivalent to the keywords begin
and end
.
(* Example Allman code indentation style in Pascal *)
procedure dosomething(x, y: Integer);
begin
while x = y do
begin
something();
something_else();
end;
end;
Consequences of this style are that the indented code is clearly set apart from the containing statement by lines that are almost all whitespace and the closing brace lines up in the same column as the opening brace. Some people feel this makes it easy to find matching braces. The blocking style also delineates the block of code from the associated control statement. Commenting out or removing a control statement or block of code, or code refactoring, are all less likely to introduce syntax errors via dangling or missing braces. Also, it is consistent with brace placement for the outer-function block.
For example, the following is still correct syntactically:
// while (x == y)
{
something();
something_else();
}
As is this:
// for (int i=0; i < x; i++)
// while (x == y)
if (x == y)
{
something();
something_else();
}
Even like this, with conditional compilation:
int c;
#ifdef HAS_GETCH
while ((c = getch()) != EOF)
#else
while ((c = getchar()) != EOF)
#endif
{
do_something(c);
}
Variant: Allman-8
A popular variant for use in education,[citation needed] Allman-8 uses the 8-space indentation tabs and 80-column limit of the Linux Kernel variant of K&R. The style purportedly helps improve readability on projectors. Also, the indentation size and column restriction help create a visual cue for identifying excessive nesting of code blocks. These advantages combine to help provide newer developers and learners implicit guidance to manage code complexity.[citation needed]
Whitesmiths style
The Whitesmiths style, also sometimes termed Wishart style, was originally used in the documentation for the first commercial C compiler, the Whitesmiths Compiler. It was also popular in the early days of Windows, since it was used in three influential Windows programming books, Programmer's Guide to Windows by Durant, Carlson & Yao, Programming Windows by Petzold, and Windows 3.0 Power Programming Techniques by Norton & Yao.
Whitesmiths, along with Allman, have been the most common bracing styles with equal popularity according to the Jargon File.[5]
This style puts the brace associated with a control statement on the next line, indented. Statements within the braces are indented to the same level as the braces.
Like Ratliff style, the closing brace is indented the same as statements within the braces.[23]
while (x == y)
{
something();
something_else();
}
final_thing();
The advantages of this style are similar to those of the Allman style. Blocks are clearly set apart from control statements. The alignment of the braces with the block emphasizes that the full block is conceptually, and programmatically, one compound statement. Indenting the braces emphasizes that they are subordinate to the control statement. The ending brace no longer lines up with the statement, but instead with the opening brace.
An example:
if (data != NULL && res > 0)
{
if (!JS_DefineProperty(cx, o, "data", STRING_TO_JSVAL(JS_NewStringCopyN(cx, data, res)), NULL, NULL, JSPROP_ENUMERATE))
{
QUEUE_EXCEPTION("Internal error!");
goto err;
}
PQfreemem(data);
}
else if (!JS_DefineProperty(cx, o, "data", OBJECT_TO_JSVAL(NULL), NULL, NULL, JSPROP_ENUMERATE))
{
QUEUE_EXCEPTION("Internal error!");
goto err;
}
else if
are treated as statement, much like the #elif
preprocessor statement.
GNU style
Like the Allman and Whitesmiths styles, GNU style puts braces on a line by themselves, indented by two spaces, except when opening a function definition, where they are not indented.[24] In either case, the contained code is indented by two spaces from the braces.
Popularised by Richard Stallman, the layout may be influenced by his background of writing Lisp code.[25] In Lisp, the equivalent to a block (a progn) is a first-class data entity, and giving it its own indentation level helps to emphasize that, whereas in C, a block is only syntax. This style can also be found in some ALGOL and XPL programming language textbooks from the 1960s and 1970s.[26][27][discuss] Although not directly related to indentation, GNU coding style also includes a space before the bracketed list of arguments to a function.
static char *
concat (char *s1, char *s2)
{
while (x == y)
{
something ();
something_else ();
}
final_thing ();
}
This style combines the advantages of Allman and Whitesmiths, thereby removing the possible Whitesmiths disadvantage of braces not standing out from the block. One disadvantage is that the ending brace no longer lines up with the statement it conceptually belongs to. Another possible disadvantage is that it might waste space by using two visual levels of indents for one conceptual level, but in reality this is unlikely because, in systems with single-level indentation, each level is usually at least 4 spaces, same as 2 * 2 spaces in GNU style.
The GNU Coding Standards recommend this style, and nearly all maintainers of GNU project software use it.[citation needed]
The GNU Emacs text editor and the GNU systems' indent command will reformat code according to this style by default.[28] Those who do not use GNU Emacs, or similarly extensible/customisable editors, may find that the automatic indentation settings of their editor are unhelpful for this style. However, many editors defaulting to KNF style cope well with the GNU style when the tab width is set to two spaces; likewise, GNU Emacs adapts well to KNF style by simply setting the tab width to eight spaces. In both cases, automatic reformatting destroys the original spacing, but automatic line indenting will work properly.
Steve McConnell, in his book Code Complete, advises against using this style: he marks a code sample which uses it with a "Coding Horror" icon, symbolizing especially dangerous code, and states that it impedes readability.[23] The Linux kernel coding style documentation also strongly recommends against this style, urging readers to burn a copy of the GNU coding standards as a "great symbolic gesture".[29]
Horstmann style
The 1997 edition of Computing Concepts with C++ Essentials by Cay S. Horstmann adapts Allman by placing the first statement of a block on the same line as the opening brace. This style is also used in examples in Jensen and Wirth's Pascal User Manual and Report.[30]
while (x == y)
{ something();
something_else();
//...
if (x < 0)
{ printf("Negative");
negative(x);
}
else
{ printf("Non-negative");
nonnegative(x);
}
}
final_thing();
This style combines the advantages of Allman by keeping the vertical alignment of the braces for readability, and identifying blocks easily, with the saving of a line of the K&R style. However, the 2003 edition now uses Allman style throughout.[31]
Pico style
This is the style used most commonly in the language Pico by its designers. Pico lacks return statements, and uses semicolons as statement separators instead of terminators. It yields this syntax:[32]
stuff(n): { x: 3 * n; y: do_stuff(x); y + x }
The advantages and disadvantages are similar to those of saving screen real estate with K&R style. An added advantage is that the starting and closing braces are consistent in application (both share space with a line of code), relative to K&R style, where one brace shares space with a line of code and one brace has a line alone.
Ratliff style
In the book Programmers at Work,[33] C. Wayne Ratliff discussed using the style below. The style begins much like 1TBS but then the closing brace lines up with the indentation of the nested block. Ratliff was the original programmer behind the popular dBase-II and -III fourth-generation programming languages. He indicated that it was originally documented in material from Digital Research Inc. This style has sometimes been termed banner style,[34] possibly for the resemblance to a banner hanging from a pole. In this style, which is to Whitesmiths as K&R is to Allman, the closing control is indented the same as the last item in the list (and thus properly loses salience)[23] The style can make visual scanning easier for some, since the headers of any block are the only thing exdented at that level (the theory being that the closing control of the prior block interferes with the visual flow of the next block header in the K&R and Allman styles). Kernighan and Plauger use this style in the Ratfor code in Software Tools.[35]
// In C
for (i = 0; i < 10; i++) {
if (i % 2 == 0) {
do_something(i);
}
else {
do_something_else(i);
}
}
or, in a markup language...
{|
|-
| lots of stuff...
more stuff
|| alternative for short lines || etc.
|}
{|
|-
... etc
|}
Styles from languages other than C
The following styles aren't conventionally used for C code, but are derived from language families which possess major differences in syntax and semantics from those in the C family. They may theoretically appear in C code written as part of a project mostly written in one of these other languages (for example, as part of a FFI), where maintaining a consistent "look and feel" to the project's codebase may locally override considerations of using conventional C style.
Lisp style
While GNU style is sometimes characterised as C code indented by a Lisp programmer, one might even go so far as to insert closing braces together in the last line of a block. This style makes indentation the only way to distinguish blocks of code, but has the advantage of containing no uninformative lines. This could easily be called the Lisp style (because this style is very common in Lisp code) or the Python style (Python has no braces, but the layout is very similar, as shown in the code blocks below). In Python, layout is a part of the language, called the off-side rule, and in Lisp, the grouping of identical braces at the end of expression trees is meant to signify that it is not the user's job to visually track nesting levels, only to understand the structure of the tree.
The traditional Lisp variant of this style prefers extremely narrow levels of indentation (typically two spaces) because Lisp code usually nests very deeply since Lisp features only expressions, with no distinct class of statements; function arguments are mostly indented to the same level to illustrate their shared status within the enclosing expression. This is also because, braces aside, Lisp is conventionally a very terse language, omitting even common forms of simple boilerplate code as uninformative, such as the else
keyword in an if : then | else
block, instead rendering it uniformly as (if expr1 expr2 expr3)
.
// In C
for (i = 0; i < 10; i++)
{if (i % 2 == 0)
{do_something(i);}
else
{do_something_else(i);
do_third_thing(i);}}
# In Python
for i in range(10):
if i % 2 == 0:
do_something(i)
else:
do_something_else(i)
do_third_thing(i)
;; In Lisp
(dotimes (i 10)
(if (= (rem i 2) 0)
(do-something i)
(progn
(do-something-else i)
(do-third-thing i))))
Note: progn
is a procedure for evaluating multiple sub-expressions sequentially for effects, while discarding all but the final (nth) return value. If all return values are desired, the values
procedure would be used.
Haskell style
Haskell layout can make the placement of braces optional, although braces and semicolons are allowed in the language.[36] The two segments below are equally acceptable to the compiler:
braceless = do
text <- getContents
let
firstWord = head $ words text
bigWord = map toUpper firstWord
putStrLn bigWord
braceful = do
{ text <- getContents
; let
{ firstWord = head $ words text
; bigWord = map toUpper firstWord
}
; putStrLn bigWord
}
In Haskell, layout can replace braces.
Usually the braces and semicolons are omitted for procedural do
sections and the program text in general, but the style is commonly used for lists, records and other syntactic elements made up of some pair of parentheses or braces, which are separated with commas or semicolons.[37] If code following the keywords where
, let
, or of
omits braces and semicolons, then indentation is significant.[38]
APL style
For an example of how terse APL typically is, here is the implementation of the step function for the Game of Life:
life←{⊃1⍵∨.∧3 4=+/+⌿¯1 0 1∘.⊖¯1 0 1⌽¨⊂⍵}
APL style C resembles the terse style of APL code, and is commonly used in their implementations.[39] This style was pioneered by Arthur Whitney, and is heavily used in the implementation of K, Arthur's own project. The J programming language is implemented in this style as well. Notably, not all implementations of APL use this style of C, namely: GNU APL and Dyalog APL.
In addition to APL style C indentation, typically the names are shortened to either single or double characters: To reduce the amount of indentation, and expressions spanning multiple lines.
Other considerations
Losing track of blocks
In some situations, there is a risk of losing track of block boundaries. This is often seen in large sections of code containing many compound statements nested to many levels of indentations. By the time the programmer scrolls to the bottom of a huge set of nested statements, they may have lost track of which control statements go where. However, overly-long code could have other causes, such as being too complex, and a programmer facing this problem might instead consider whether code refactoring would help in the longer term.
Programmers who rely on counting the opening braces may have difficulty with indentation styles such as K&R, where the starting brace is not visually separated from its control statement. Programmers who rely more on indentations will gain more from styles that are vertically compact, such as K&R, because the blocks are shorter.
To avoid losing track of control statements such as for
, a large indentation can be used, such as an 8-unit-wide hard tab, along with breaking up large functions into smaller and more readable functions. Linux is done this way, while using the K&R style.
In text editors of the vi family, one means to track block boundaries is to position the text cursor over one of the braces, and press the %
key. The cursor then jumps to the opposing brace. Since the text cursor's next
key (viz., the n
key) retained directional positioning information (whether the up
or down
key was formerly pressed), the dot macro (the .
key) could then be used to place the text cursor on the next brace,[40] given a suitable coding style. Instead, inspecting the block boundaries using the %
key can be used to enforce a coding standard.
Another way is to use inline comments added after the closing brace:
for (int i = 0; i < total; i++) {
foo(bar);
} //for (i)
if (x < 0) {
bar(foo);
} //if (x < 0)
The major disadvantage of this method is maintaining duplicate code in multiple locations.
Another solution is implemented in a folding editor, which can hide or reveal blocks of code via their indentation level or compound-statement structure. Many editors will also highlight matching brackets or braces when the cursor is positioned next to one.
Statement insertion
K&R style prevents another common error suffered when using the standard Unix line editor, ed. A statement mistakenly inserted between the control statement and the opening brace of the loop block turns the body of the loop into a single trip.
for (int i = 0; i < 10; i++)
whoops(bar); /* repeated 10 times, with i from 0 to 9 */
{
only_once(); /* Programmer intended this to be done 10 times */
} //for (i) ← This comment is no longer valid, and is very misleading!
K&R style avoids this problem by keeping the control statement and the opening brace on the same line.
See also
- Secondary notation
- Syntax highlighting
- Indentation in programming
- Bachmanity Insanity, a Silicon Valley episode featuring the topic
- Source-code formatter
References
- ^ Zawinski, Jamie (2000). "Tabs versus Spaces: An Eternal Holy War". Retrieved 6 June 2016.
- ^ "WordPress Coding Standards". Retrieved 6 June 2016.
- ^ Hoffa, Felipe (26 July 2017). "400,000 GitHub repositories, 1 billion files, 14 terabytes of code: Spaces or Tabs?". Medium. Retrieved 9 July 2019.
- ^ Miara, Richard J.; Musselman, Joyce A.; Navarro, Juan A. & Shneiderman, Ben (November 1983). "Program Indentation and Comprehensibility" (PDF). Communications of the ACM. 26 (11): 861–867. doi:10.1145/182.358437. S2CID 11767796. Retrieved 3 August 2017.
- ^ a b c "The Jargon File". 4.4.7. 29 December 2003. Retrieved 18 August 2014.
- ^ Darwin, Ian F. (1988). Checking C programs with Lint. California: O'Reilly and Assosciates. p. 51. ISBN 9780937175309.
- ^ a b "1TBS".
- ^ "Java Style Guide". Archived from the original on 12 July 2018.
Using either "Egyptian" curly braces or C-style curly braces is acceptable
- ^ "Egyptian brackets". Foldoc.
A humourous [sic] term for K&R indent style, referring to the "one hand up in front, one down behind" pose
- ^ "Google JavaScript Style Guide".
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs
- ^ a b "Brace styles and JavaScript". 7 January 2013. Retrieved 8 November 2018.
- ^ A detailed description of the style is given at kernel.org.
- ^ Larabel, Michael. "The Linux Kernel Deprecates The 80 Character Line Coding Style". Phoronix. Phoronix Media. Retrieved 1 May 2022.
- ^ Reddy, Achut (30 March 2000). "Java Coding Style Guide" (PDF). Sun Microsystems. Archived from the original (PDF) on 28 February 2006. Retrieved 30 May 2008.
- ^ "Java Code Conventions" (PDF). Sun Microsystems. 12 September 1997. Archived from the original (PDF) on 13 May 2008. Retrieved 30 May 2008.
- ^ "Code Conventions for the Java Programming Language". Sun Microsystems. 20 March 1997. Retrieved 30 May 2008.
- ^ a b Stroustrup, Bjarne (September 2010). "PPP Style Guide" (PDF).
- ^ Stroustrup, Bjarne. "C++ Core Guidelines". GitHub. Retrieved 3 November 2018.
- ^ a b c Shannon, Bill (19 August 1996). "C Style and Coding Standards for SunOS" (PDF). 1.8. Sun Microsystems, Inc. Retrieved 15 June 2019.
- ^ a b Gregg, Brendan. "DTraceToolkit Style Guide". Retrieved 6 February 2015.
- ^ Shannon, Bill (9 September 1998). "cstyle.pl". illumos-gate. 1.58. Sun Microsystems, Inc. Retrieved 6 February 2015.
- ^ "indent style". The on-line hacker Jargon File. 4.4.7. 29 December 2003. Retrieved 20 March 2022 – via catb.
- ^ a b c McConnell, Steve (2004). Code Complete: A practical handbook of software construction. Redmond, WA: Microsoft Press. pp. 746–747. ISBN 978-0-7356-1967-8.
- ^ a b "Formatting Your Source Code". GNU Coding Standards. Retrieved 6 June 2016.
- ^ Stallman, Richard (28 October 2002). "My Lisp Experiences and the Development of GNU Emacs (Transcript of speech at the International Lisp Conference)". Retrieved 6 June 2016.
- ^ Baumann, Richard [in German]; Feliciano, Manuel; Bauer, Friedrich Ludwig; Samelson, Klaus (1964). Introduction to ALGOL – A primer for the non-specialist, emphasizing the practical uses of the algorithmic language. Series in Automatic Computation. Englewood Cliffs, New Jersey, USA: Prentice-Hall, Inc. ISBN 0-13-477828-6. LCCN 64-10740. ark:/13960/t6qz35p37. Retrieved 23 October 2022.
- ^ W. M. McKeeman, J. J. Horning, and D. B. Wortman, A Compiler Generator, 1970, https://archive.org/details/compilergenerato00mcke
- ^ Tested on the sample source code above on Ubuntu 18.04 with GNU indent 2.2.11 and GNU Emacs 25.2.2 started with
emacs --no-init-file
. - ^ "Linux kernel coding style". Retrieved 1 January 2017.
- ^ Jensen, Kathleen; Wirth, Niklaus (1974). PASCAL User Manual and Report. Springer-Verlag.
- ^ Horstmann Style Guide
- ^ Ohno, Asako (2013). "A methodology to teach exemplary coding style considering students' coding style feature contains fluctuations". 2013 IEEE Frontiers in Education Conference (FIE). pp. 1908–1910. doi:10.1109/fie.2013.6685167. ISBN 9781467352611. S2CID 28385526.
- ^ Lammers, Susan (1986). Programmers at Work. Microsoft Press. ISBN 978-0-914845-71-3.
- ^ Pattee, Jim. "Artistic Style 2.05 Documentation". Artistic Style. Retrieved 24 April 2015.
- ^ Kernighan, Brian W.; Plauger, P. J. (1976). Software Tools. Addison-Wesley. ISBN 9780201036695.
- ^ "The Haskell 98 Report". haskell.org. Retrieved 3 March 2016.
- ^ Lipovača, Miran. "Making Our Own Types and Typeclasses". learnyouahaskell.com. Retrieved 3 February 2016.
- ^ Haskell Report 1.2 (1992), p.131 B.4 "Layout"
- ^ "The J Incunabulum". jsoftware.com. Retrieved 19 May 2022.
- ^ Lamb, Linda (1998). Learning the vi editor. O'Reilly. ISBN 9781565924260.
External links
- C Style: Standards and Guidelines: Defining Programming Standards for Professional C Programmers, Prentice Hall, ISBN 0-13-116898-3 / ISBN 978-0-13-116898-5 (full text is also online). Straker, David (1992).
- Contextual Indent
- GNU Coding Standards
- Source Code Formatters at Curlie
Tabs and spaces
- Tabs versus Spaces: An Eternal Holy War by Jamie Zawinski
- Why I prefer no tabs in source code by Adam Spiers
- Why I love having tabs in source code (archived)
- Elastic tabstops – the solution to the tabs-versus-spaces issue