Jump to content

Indentation style: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Statement insertion: Use encyclopedic style instead of instructional. Code comment wouldn't be changed in real life.
m fixed grammar
(34 intermediate revisions by 12 users not shown)
Line 3: Line 3:
{{Use dmy dates|date=October 2022}}
{{Use dmy dates|date=October 2022}}


In [[computer programming]], '''indentation style''' is a [[Convention (norm)|convention]], a.k.a. [[programming style|style]], governing the [[Indentation (typesetting)|indentation]] of [[Block (programming)|blocks]] of [[source code]] that is intended to result in code that conveys structure.
In [[computer programming]], '''indentation style''' is a [[Convention (norm)|convention]], a.k.a. [[programming style|style]], governing the [[Indentation (typesetting)|indentation]] of [[Block (programming)|blocks]] of [[source code]]. An indentation style generally involves consistent width of [[whitespace characters|whitespace]] (indentation size) before each line of a block, so that the lines of code appear to be related, and dictates whether to use [[Space (punctuation)|space]] or [[Tab character|tab]] characters for the indentation whitespace.


== Overview ==
Indentation involves using the same width of [[whitespace characters|whitespace]] before each line of a group of code so that they appear to be related. As whitespace consists of both [[Space (punctuation)|space]] and [[Tab character|tab]] characters, a [[programmer]] can choose which to use {{endash}}
often entering them via the [[space key]] or [[tab key]] on the [[computer keyboard|keyboard]].

Indentation applies to a text-based [[programming language]]. This article primarily addresses [[free-form language]]s, with special attention to
[[curly-bracket languages]] (that delimit blocks with [[curly bracket|curly brackets, a.k.a. curly braces, a.k.a. braces]]) and in particular
[[List of C-family programming languages|C-family languages]].


As the name implies, free-form language code need not follow an indentation style. Indentation is a [[secondary notation]] that is often intended to lower [[cognitive load]] for a programmer to understand the structure of the code.
This article primarily addresses styles for [[free-form language|free-form]] [[programming language]]s. As the name implies, such language code need not follow an indentation style. Indentation is a [[secondary notation]] that is often intended to lower [[cognitive load]] for a programmer to understand the structure of the code.
Indentation can clarify the separation between the code executed based on [[control flow]].
Indentation can clarify the separation between the code executed based on [[control flow]].


Structured languages, such as [[Python (programming language)|Python]] and [[occam (programming language)|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 language processor (such as [[compiler]] or [[Interpreter (computing)|interpreter]]). A programmer must conform to the language's indentation rules although may be free to choose indentation size.
Some free-from languages use keywords instead of braces {{endash}} for example <code>BEGIN</code> and <code>END</code>.


This article focuses on [[curly-bracket languages]] (that delimit blocks with [[curly bracket|curly brackets, a.k.a. curly braces, a.k.a. braces]]) and in particular
Structured languages, such as [[Python (programming language)|Python]] and [[occam (programming language)|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 language processor (such as [[compiler]] or [[Interpreter (computing)|interpreter]]); not just the programmer.
[[List of C-family programming languages|C-family languages]], but a convention used for one language can be adapted to another language. For example, a language that uses <code>BEGIN</code> and <code>END</code> keywords instead of braces can be adapted by treating <code>BEGIN</code> the same as the open brace and so on.


Indentation style only applies to text-based languages. [[Visual programming language]]s have no indentation.
A convention used for one language can be adapted for another language.{{Explain|date=March 2024}}


== Overview ==
== Research ==

Despite the ubiquitous use of indentation styles, little research has been conducted on its value. First experiments, conducted by Weissman in 1974, did not show any effect.<ref>{{Cite tech report |last=Weissman |first=Laurence Mark |url=https://archive.org/details/technicalreportc37univ |title=A Methodology For Studying The Psychological Complexity of Computer Programs |publisher=Computer Systems Research Group, [[University of Toronto]] |work=CSRG-37 |id=technicalreportc37univ |via=[[Internet Archive]] |year=1974 |oclc=1085612768 |language=en}}</ref>
In 2023, an experiment by Morzeck et al.<ref>{{Cite conference |first1=Johannes |last1=Morzeck |url=https://drive.google.com/file/d/1UACm8yWCVVdghZw9m6x79fivRzixDubs/view |title=Indentation in Source Code: A Randomized Control Trial on the Readability of Control Flows in Java Code with Large Effects |last2=Hanenberg |first2=Stefan |last3=Werger |first3=Ole |last4=Gruhn |first4=Volker |year=2023 |conference=Proceedings of the 18th International Conference on Software Technologies - ICSOFT | pages=117–128 |doi=10.5220/0012087500003538 |isbn=978-989-758-665-1 |location=[[Rome]], Italy |via=Stefan Hanenberg on [[Google Drive]] (preprint) |language=en|doi-access=free }}</ref> showed significant positive effect for nested <code>if</code> statements where non-indented code required on average 179% more time to read than indented code.

== Notable styles ==


The table below includes code examples of various indentation styles.
The table below includes code examples of various indentation styles.
Line 41: Line 42:
while (x == y)
while (x == y)
{
{
foo ();
foo();
bar();
bar();
}
}
</syntaxhighlight>
</syntaxhighlight>
| [[#GNU style|GNU]]
| [[#GNU|GNU]]
|-
|-
| style="padding: 0 4px" | <syntaxhighlight lang=c>
| style="padding: 0 4px" | <syntaxhighlight lang=c>
Line 54: Line 55:
}
}
</syntaxhighlight>
</syntaxhighlight>
| [[#Whitesmiths style|Whitesmiths]]
| [[#Whitesmiths|Whitesmiths]]
|-
|-
| style="padding: 0 4px" | <syntaxhighlight lang=c>
| style="padding: 0 4px" | <syntaxhighlight lang=c>
Line 62: Line 63:
}
}
</syntaxhighlight>
</syntaxhighlight>
| [[#K&R style|K&R]]
| [[#K&R|K&R]]
|-
|-
| style="padding: 0 4px" | <syntaxhighlight lang=c>
| style="padding: 0 4px" | <syntaxhighlight lang=c>
Line 70: Line 71:
}
}
</syntaxhighlight>
</syntaxhighlight>
| [[#Ratliff style|Ratliff]]
| [[#Ratliff|Ratliff]]
|-
|-
| style="padding: 0 4px" | <syntaxhighlight lang=c>
| style="padding: 0 4px" | <syntaxhighlight lang=c>
Line 78: Line 79:
}
}
</syntaxhighlight>
</syntaxhighlight>
| [[#Horstmann style|Horstmann]]
| [[#Horstmann|Horstmann]]
|-
|-
| style="padding: 0 4px" | <syntaxhighlight lang=c>
| style="padding: 0 4px" | <syntaxhighlight lang=c>
Line 85: Line 86:
bar(); }
bar(); }
</syntaxhighlight>
</syntaxhighlight>
| [[#Pico style|Pico]]
| [[#Pico|Pico]]
|-
|-
| style="padding: 0 4px" | <syntaxhighlight lang=c>
| style="padding: 0 4px" | <syntaxhighlight lang=c>
Line 110: Line 111:
== C/C++ styles ==
== C/C++ styles ==


Attributes of [[C language|C]], [[C++]] and other [[curly-brace programming language]] coding style include but are not limited to:
The main difference between C/C++ indentation styles covered here is the placement of braces relative to other code elements.
* Placement of [[curly braces|braces]] relative to other code elements
* Use of [[tab character|tabs]] or [[space character|spaces]]
* Wrapping single-statement blocks in braces. Advocates cite the advantage that resulting code is safer since inserting a statement cannot result in control flow that disagrees with indentation. A cited disadvantage is that the code is longer since one line is needed for the closing brace of a block (except for the <code>else if</code> construct and a <code>do{}while</code> block).


=== K&R ===
The relative placement is sometimes different for the body of a function vs. a compound statement (<code>if</code>, <code>while</code>, <code>for</code>, ...)


The Kernighan & Ritchie (K&R) style is commonly used for C and C++ code and is the basis for many derivative styles. It is used in the original Unix kernel, [[Brian Kernighan|Kernighan]] and [[Dennis Ritchie|Ritchie's]] book ''[[The C Programming Language]]'', as well as Kernighan and [[P. J. Plauger|Plauger]]'s book ''[[The Elements of Programming Style]]''.
===K&R style===


Although ''[[The C Programming Language]]'' does not explicitly define this style, it follows it consistently. From the book:
{{anchor|1TBS|OTBS|1TBF}}
<blockquote>
The Kernighan & Ritchie (K&R) style, and the closely related "one true brace style" in hacker jargon<ref name=jargon>{{cite web |url=http://www.catb.org/jargon/html/I/indent-style.html |title=The Jargon File |version=4.4.7 |date=29 December 2003 |access-date=18 August 2014}}</ref><ref>{{cite book |url={{google books|id=vweTteq3OLQC|page=51|plain-url=yes}} |title=Checking C programs with Lint |first=Ian F. |last=Darwin |publisher=O'Reilly and Assosciates |location=California |page=51 |isbn=9780937175309|year=1988 }}</ref> (abbreviated as 1TBS<ref name="catb.org">{{Cite web|url=http://catb.org/jargon/html/0/one-TBS.html|title=1TBS}}</ref>), are commonly used in C, [[C++]], and other [[curly-brace programming language]]s. It was the style used in the original Unix kernel, [[Brian Kernighan|Kernighan]] and [[Dennis Ritchie|Ritchie's]] book ''[[The C Programming Language]]'', as well as Kernighan and [[P. J. Plauger|Plauger]]'s book ''[[The Elements of Programming Style]]''.
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.
</blockquote>


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.
In this style, a function has its opening and closing braces on their own lines and with the same indentation as the declaration, and with statements indented an additional level than the declaration. A multi-statement block inside a function, however, has its opening brace on the same line as its control clause while the closing brace remains on its own line unless followed by a keyword such as <code>else</code> or <code>while</code>.


Example code:
{{anchor|Egyptian}} 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 <code>else</code> or <code>while</code>. Such non-[[typographic alignment|aligned]] braces are nicknamed "Egyptian braces" (or "Egyptian brackets") for their resemblance to arms in some fanciful poses of ancient Egyptians.<ref>{{cite web |title=Java Style Guide |url=https://www.seas.upenn.edu/~cis120/current/java_style.shtml#f |quote=Using either "Egyptian" curly braces or C-style curly braces is acceptable |url-status=dead |archive-url=https://web.archive.org/web/20180712222126/https://www.seas.upenn.edu/~cis120/current/java_style.shtml |archive-date=2018-07-12}}</ref><ref>{{cite web |title=Egyptian brackets |url=http://foldoc.org/Egyptian+brackets |website=[[Foldoc]] |quote=A {{sic|humou|rous}} term for K&R indent style, referring to the "one hand up in front, one down behind" pose}}</ref><ref>{{cite web |title=Google JavaScript Style Guide |url=https://google.github.io/styleguide/jsguide.html#formatting-nonempty-blocks |quote=Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs}}</ref> 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 [[Unreachable_code#goto_fail_bug|goto fail bug]]).


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
int main(int argc, char *argv[])
int main(int argc, char *argv[])
{
{
...
while (x == y) {
while (x == y) {
something();
do_something();
something_else();
do_something_else();

if (some_error)
if (some_error)
do_correct(); // In K&R a single-statement block does not have braces.
fix_issue(); // single-statement block without braces
else
else
continue_as_usual();
continue_as_usual();
}
}

final_thing();
final_thing();
...
}
}
</syntaxhighlight>
</syntaxhighlight>


==== Egyptian braces ====
''[[The C Programming Language]]'' book does not explicitly specify this style, though it follows it consistently throughout. From the book:
<blockquote>
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.
</blockquote>


{{anchor|Egyptian}}
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):
The non-[[typographic alignment|aligned]] braces of the multi-line blocks are nicknamed "Egyptian braces" (or "Egyptian brackets") for their resemblance to arms in some fanciful poses of ancient Egyptians.<ref>{{cite web |title=Java Style Guide |url=https://www.seas.upenn.edu/~cis120/current/java_style.shtml#f |quote=Using either "Egyptian" curly braces or C-style curly braces is acceptable |url-status=dead |archive-url=https://web.archive.org/web/20180712222126/https://www.seas.upenn.edu/~cis120/current/java_style.shtml |archive-date=2018-07-12}}</ref><ref>{{cite web |title=Egyptian brackets |url=http://foldoc.org/Egyptian+brackets |website=[[Foldoc]] |quote=A {{sic|humou|rous}} term for K&R indent style, referring to the "one hand up in front, one down behind" pose}}</ref><ref>{{cite web |title=Google JavaScript Style Guide |url=https://google.github.io/styleguide/jsguide.html#formatting-nonempty-blocks |quote=Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs}}</ref>


==== Single statements ====
<syntaxhighlight lang=c>
/* Original pre-ISO C style without function prototypes */
int main(argc, argv)
int argc;
char *argv[];
{
...
}
</syntaxhighlight>


A single-statement block does not have braces, which is a cause of easy-to-miss bugs such as the [[Unreachable_code#goto_fail_bug|goto fail bug]].
{{anchor|Variant: 1TBS}}


====Variant: 1TBS (OTBS)====
=== One True Brace ===
The "one true brace style" (abbreviated as 1TBS or OTBS<ref name="catb.org"/>) 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.<ref name=onetruestyle>{{cite web |url=http://2ality.com/2013/01/brace-styles.html |title=Brace styles and JavaScript |date=7 January 2013 |access-date=8 November 2018}}</ref>


{{anchor|Variant: 1TBS}}
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 [[Unreachable_code#goto_fail_bug|goto fail bug]]).
{{anchor|1TBS|OTBS|1TBF}}


The ''One True Brace Style'' <ref>{{cite book |url={{google books|id=vweTteq3OLQC|page=51|plain-url=yes}} |title=Checking C programs with Lint |first=Ian F. |last=Darwin |publisher=O'Reilly and Assosciates |location=California |page=51 |isbn=9780937175309|year=1988 }}</ref> (abbreviated 1TBS or OTBS<ref name="catb.org">{{Cite web|url=http://catb.org/jargon/html/0/one-TBS.html|title=1TBS}}</ref>) is like the K&R style, but functions are formatted like multi-statement blocks with the opening brace on the same line as the declaration, and braces are ''not'' omitted for a single-statement block.<ref name=onetruestyle>{{cite web |url=http://2ality.com/2013/01/brace-styles.html |title=Brace styles and JavaScript |date=7 January 2013 |access-date=8 November 2018}}</ref>
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:


<syntaxhighlight lang=c>
<syntaxhighlight lang="cpp">
bool is_negative(x) {
bool is_negative(int x) {
if (x < 0) {
if (x < 0) {
return true;
return true;
Line 178: Line 170:
</syntaxhighlight>
</syntaxhighlight>


Although not required by languages such as C/C++, using braces for single-statement blocks ensures that inserting a statement does not result in control flow that disagrees with indenting, as seen for example in Apple's infamous [[Unreachable_code#goto_fail_bug|goto fail bug]].
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,<ref name=onetruestyle /> while others note that it as just another "hacker jargon" term for K&R.<ref name=jargon/>


Cited advantages include shorter code (than K&R) since the starting brace needs no extra line, and the ending brace lines up with the statement it conceptually belongs to. One cost of this style is that the ending brace adds a line, which can be partly resolved in if/else blocks and do/while blocks.
====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]].<ref>A detailed description of the style is given at [https://www.kernel.org/doc/html/latest/process/coding-style.html kernel.org].</ref> [[Linus Torvalds]] strongly advises all contributors to follow it. The style borrows many elements from K&R.


Sources disagree as to the meaning of One True Brace Style. Some say that it is the variation specified here,<ref name=onetruestyle /> while others say it is "hacker jargon" for K&R.<ref name=jargon>{{cite web |url=http://www.catb.org/jargon/html/I/indent-style.html |title=The Jargon File |version=4.4.7 |date=29 December 2003 |access-date=18 August 2014}}</ref>
The kernel style uses [[tab stop]]s (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 <code>switch</code> statement are aligned with the enclosing block (there is only one level of indents). Line length used to be limited to 80 characters{{snd}} it was raised to 100 in 2020, but the original limit is still preferred.<ref>{{cite web |last1=Larabel |first1=Michael |title=The Linux Kernel Deprecates The 80 Character Line Coding Style |url=https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kernel-Deprecates-80-Col |website=Phoronix |publisher=Phoronix Media |access-date=1 May 2022}}</ref> 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 <code>if-else</code> statement require braces, then both substatements should be wrapped inside curly braces:

=== Linux kernel ===

The [[Linux kernel]] source tree is styled in a variant of K&R.<ref>A detailed description of the style is given at [https://www.kernel.org/doc/html/latest/process/coding-style.html kernel.org].</ref> [[Linus Torvalds]] advises contributors to follow it. Attributes include:

* Uses [[tab character]]s for indentation (not spaces) and assumes [[tab stop]]s every 8 spaces
* Brace layout matches K&R with open and close on their own lines and multi-statement open on same line as the control clause, separated by a space
* Labels in a <code>switch</code> statement are aligned with the enclosing block (there is only one level of indents)
* Maximum line length is 100 characters although the pre-2020 limit of 80 characters is preferred.<ref>{{cite web |last1=Larabel |first1=Michael |title=The Linux Kernel Deprecates The 80 Character Line Coding Style |url=https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kernel-Deprecates-80-Col |website=Phoronix |publisher=Phoronix Media |access-date=1 May 2022}}</ref>
* A single-statement body of a compound statement (such as if, while, and do-while) does not need to be surrounded by curly braces. If, however, one or more of the substatements in an <code>if-else</code> statement require braces, then both substatements should be wrapped in braces:


<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
Line 201: Line 202:
</syntaxhighlight>
</syntaxhighlight>


====Variant: mandatory braces====
=== Java ===
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).


A significant body of [[Java (programming language)|Java]] code uses a 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.
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 (programming language)|Java]] is sometimes written in other styles, a significant body of Java code uses a minor variant of the [[#K&R style|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<ref>{{cite web |url=http://developers.sun.com/prodtech/cc/products/archive/whitepapers/java-style.pdf |title=Java Coding Style Guide |last=Reddy |first=Achut |publisher=Sun Microsystems |date=30 March 2000 |access-date=30 May 2008 |url-status=dead |archive-url=https://web.archive.org/web/20060228095122/http://developers.sun.com/prodtech/cc/products/archive/whitepapers/java-style.pdf |archive-date=28 February 2006}}</ref><ref>{{cite web |url=http://java.sun.com/docs/codeconv/CodeConventions.pdf |title=Java Code Conventions |publisher=Sun Microsystems |date=12 September 1997 |access-date=30 May 2008 |url-status=dead |archive-url=https://web.archive.org/web/20080513084244/http://java.sun.com/docs/codeconv/CodeConventions.pdf |archive-date=13 May 2008}}</ref><ref>{{cite web
This style is widespread largely because [[Sun Microsystems]]'s original style guides<ref>{{cite web |url=http://developers.sun.com/prodtech/cc/products/archive/whitepapers/java-style.pdf |title=Java Coding Style Guide |last=Reddy |first=Achut |publisher=Sun Microsystems |date=30 March 2000 |access-date=30 May 2008 |url-status=dead |archive-url=https://web.archive.org/web/20060228095122/http://developers.sun.com/prodtech/cc/products/archive/whitepapers/java-style.pdf |archive-date=28 February 2006}}</ref><ref>{{cite web |url=http://java.sun.com/docs/codeconv/CodeConventions.pdf |title=Java Code Conventions |publisher=Sun Microsystems |date=12 September 1997 |access-date=30 May 2008 |url-status=dead |archive-url=https://web.archive.org/web/20080513084244/http://java.sun.com/docs/codeconv/CodeConventions.pdf |archive-date=13 May 2008}}</ref><ref>{{cite web
| url=http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
| url=http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
Line 215: Line 212:
| access-date=30 May 2008}}</ref> used this K&R variant, and as a result, most of the standard source code for the [[Java Class Library|Java API]] is written in this style. It is also a popular indentation style for [[ActionScript]] and [[JavaScript]], along with the [[#Allman style|Allman style]].
| access-date=30 May 2008}}</ref> used this K&R variant, and as a result, most of the standard source code for the [[Java Class Library|Java API]] is written in this style. It is also a popular indentation style for [[ActionScript]] and [[JavaScript]], along with the [[#Allman style|Allman style]].


====Variant: Stroustrup====
=== 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]]''.<ref name="ppp">{{cite web |url=https://www.stroustrup.com/Programming/PPP-style.pdf |title=PPP Style Guide |first=Bjarne |last=Stroustrup |date=September 2010}}</ref>
[[Bjarne Stroustrup]] adapted the K&R style for C++ in his books, such as ''Programming: Principles and Practice using C++'' and ''[[The C++ Programming Language]]''.<ref name="ppp">{{cite web |url=https://www.stroustrup.com/Programming/PPP-style.pdf |title=PPP Style Guide |first=Bjarne |last=Stroustrup |date=September 2010}}</ref>


Unlike the variants above, Stroustrup does not use a "cuddled else". Thus, Stroustrup would write<ref name="ppp" />
Unlike the variants above, Stroustrup does not use a "cuddled else". Thus, Stroustrup would write<ref name="ppp" />
Line 253: Line 251:
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''.<ref>{{cite web |last1=Stroustrup |first1=Bjarne |title=C++ Core Guidelines |url=https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl17-use-kr-derived-layout |website=GitHub |access-date=3 November 2018}}</ref>
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''.<ref>{{cite web |last1=Stroustrup |first1=Bjarne |title=C++ Core Guidelines |url=https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl17-use-kr-derived-layout |website=GitHub |access-date=3 November 2018}}</ref>


====Variant: BSD KNF====
=== 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 (computing)|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.<ref name="C Style and Coding Standards for SunOS">{{cite news |last1=Shannon |first1=Bill |title=C Style and Coding Standards for SunOS |url=https://www.cis.upenn.edu/~lee/06cse480/data/cstyle.ms.pdf |access-date=15 June 2019 |version=1.8 |publisher=Sun Microsystems, Inc. |date=19 August 1996}}</ref>
The [[Berkeley Software Distribution]] (BSD) operating systems uses a style that is sometimes termed [[Kernel Normal Form]] (KNF). Although mostly intended for kernel code, it is also widely used in [[userland (computing)|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.<ref name="C Style and Coding Standards for SunOS">{{cite news |last1=Shannon |first1=Bill |title=C Style and Coding Standards for SunOS |url=https://www.cis.upenn.edu/~lee/06cse480/data/cstyle.ms.pdf |access-date=15 June 2019 |version=1.8 |publisher=Sun Microsystems, Inc. |date=19 August 1996}}</ref>


The SunOS kernel and userland uses a similar indentation style.<ref name="C Style and Coding Standards for SunOS" /> Like KNF, this also was based on AT&T style documents and is sometimes termed Bill Joy Normal Form.<ref name="DTraceToolkit Style Guide">{{cite web |last1=Gregg |first1=Brendan |title=DTraceToolkit Style Guide |url=http://www.brendangregg.com/DTraceToolkit/style.html |access-date=6 February 2015}}</ref> 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.<ref name="C Style and Coding Standards for SunOS" /><ref name="DTraceToolkit Style Guide" /><ref name="illumos-gate cstyle">{{cite web |url=https://github.com/illumos/illumos-gate/blob/master/usr/src/tools/scripts/cstyle.pl |title=cstyle.pl |last1=Shannon |first1=Bill |date=9 September 1998 |website=illumos-gate |publisher=Sun Microsystems, Inc. |access-date=6 February 2015 |version=1.58}}</ref>
The SunOS kernel and userland uses a similar indentation style.<ref name="C Style and Coding Standards for SunOS" /> Like KNF, this also was based on AT&T style documents and is sometimes termed Bill Joy Normal Form.<ref name="DTraceToolkit Style Guide">{{cite web |last1=Gregg |first1=Brendan |title=DTraceToolkit Style Guide |url=http://www.brendangregg.com/DTraceToolkit/style.html |access-date=6 February 2015}}</ref> 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.<ref name="C Style and Coding Standards for SunOS" /><ref name="DTraceToolkit Style Guide" /><ref name="illumos-gate cstyle">{{cite web |url=https://github.com/illumos/illumos-gate/blob/master/usr/src/tools/scripts/cstyle.pl |title=cstyle.pl |last1=Shannon |first1=Bill |date=9 September 1998 |website=illumos-gate |publisher=Sun Microsystems, Inc. |access-date=6 February 2015 |version=1.58}}</ref>
Line 262: Line 261:
Moreover, function calls do not use a space before the parenthesis, although C-language native statements such as <code>if</code>, <code>while</code>, <code>do</code>, <code>switch</code> and <code>return</code> do (in the case where <code>return</code> 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.
Moreover, function calls do not use a space before the parenthesis, although C-language native statements such as <code>if</code>, <code>while</code>, <code>do</code>, <code>switch</code> and <code>return</code> do (in the case where <code>return</code> 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.


Examples:
Here follow a few samples:


<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
Line 302: Line 301:
</syntaxhighlight>
</syntaxhighlight>


===Allman style===
=== Allman ===
{{anchor|Allman|Allman style|BSD/Allman style}}
{{anchor|Allman|Allman style|BSD/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 [[Berkeley Software Distribution|BSD]] Unix (although this should not be confused with the different "BSD KNF style"; see above).
The Allman style is named after [[Eric Allman]]. It is also sometimes termed ''BSD style'' since Allman wrote many of the utilities for [[Berkeley Software Distribution|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.<ref name= allman >{{cite web |url=http://www.catb.org/jargon/html/I/indent-style.html |title=indent style |work=The on-line hacker Jargon File |via=catb |access-date=2022-03-20 |version=4.4.7 |date=2003-12-29}}</ref>
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.<ref name="jargon"/>

<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
while (x == y)
while (x == y)
Line 330: Line 331:
end;
end;
</syntaxhighlight>
</syntaxhighlight>

Consequences of this style are that the indented code is clearly set apart from the containing statement by lines that are almost all [[Whitespace character|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.
Consequences of this style are that the indented code is clearly set apart from the containing statement by lines that are almost all [[Whitespace character|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:
For example, the following is still correct syntactically:

<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
// while (x == y)
// while (x == y)
Line 350: Line 353:
}
}
</syntaxhighlight>
</syntaxhighlight>

Even like this, with conditional compilation:
Even like this, with conditional compilation:

<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
int c;
int c;
Line 363: Line 368:
</syntaxhighlight>
</syntaxhighlight>


====Variant: Allman-8====
==== Variant: Allman-8 ====
A popular variant for use in education,{{Citation needed|date=October 2016}} 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|date=October 2016}}
A popular variant for use in education,{{Citation needed|date=October 2016}} 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|date=October 2016}}


===Whitesmiths style===
=== Whitesmiths ===
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 [[David Durant|Durant]], [[Geta Carlson|Carlson]] & [[Paul Yao|Yao]], ''[[Programming Windows]]'' by [[Charles Petzold|Petzold]], and ''[[Windows 3.0 Power Programming Techniques]]'' by [[Peter Norton|Norton]] & Yao.
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 [[David Durant|Durant]], [[Geta Carlson|Carlson]] & [[Paul Yao|Yao]], ''[[Programming Windows]]'' by [[Charles Petzold|Petzold]], and ''[[Windows 3.0 Power Programming Techniques]]'' by [[Peter Norton|Norton]] & Yao.


Whitesmiths, along with [[#Allman style|Allman]], have been the most common bracing styles with equal popularity according to the [[Jargon File]].<ref name=jargon/>
Whitesmiths, along with [[#Allman style|Allman]], were claimed to have been the most common bracing styles in 1991 by the [[Jargon File]], with roughly equal popularity at the time.<ref name=jargon/><ref name="jargon243">{{cite web |url=http://www.catb.org/~esr/jargon/oldversions/jarg243.txt |title=The Jargon File (Version 2.4.3) |version=2.4.3 |date=23 January 1991 |access-date=14 May 2024}}</ref>


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.
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.
Line 388: Line 393:


An example:
An example:

<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
if (data != NULL && res > 0)
if (data != NULL && res > 0)
Line 407: Line 413:
<code>else if</code> are treated as statement, much like the <code>#elif</code> preprocessor statement.
<code>else if</code> are treated as statement, much like the <code>#elif</code> preprocessor statement.


===GNU style===
=== GNU ===
{{Main article|GNU coding standards}}
{{Main article|GNU coding standards}}

Like the [[#Allman style|Allman]] and [[#Whitesmiths style|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.<ref name="gnu.org">{{cite web
Like the [[#Allman style|Allman]] and [[#Whitesmiths|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.<ref name="gnu.org">{{cite web
|url=https://www.gnu.org/prep/standards/html_node/Formatting.html
|url=https://www.gnu.org/prep/standards/html_node/Formatting.html
|title=Formatting Your Source Code
|title=Formatting Your Source Code
Line 416: Line 423:
}}</ref> In either case, the contained code is indented by two spaces from the braces.
}}</ref> 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 (programming language)|Lisp]] code.<ref name="gnu.org-lisp">{{cite web |url=https://www.gnu.org/gnu/rms-lisp.html |title=My Lisp Experiences and the Development of GNU Emacs (Transcript of speech at the International Lisp Conference) |first=Richard |last=Stallman |date=28 October 2002 |access-date=6 June 2016}}</ref> 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.<ref>{{cite book |author-last1=Baumann |author-first1=Richard |author-link1=:de:Richard Baumann (Mathematiker) |author-last2=Feliciano |author-first2=Manuel<!--, Jr.? --> |author-last3=Bauer |author-first3=Friedrich Ludwig |author-link3=Friedrich Ludwig Bauer |author-last4=Samelson |author-first4=Klaus |author-link4=Klaus Samelson |date=1964 |title=Introduction to ALGOL – A primer for the non-specialist, emphasizing the practical uses of the algorithmic language |series=Series in Automatic Computation |publisher=[[Prentice-Hall, Inc.]] |publication-place=Englewood Cliffs, New Jersey, USA |isbn=0-13-477828-6 |lccn=64-10740 |id=ark:/13960/t6qz35p37 |url=https://archive.org/details/introductiontoal00baum |access-date=2022-10-23}}</ref><ref>W. M. McKeeman, J. J. Horning, and D. B. Wortman, ''A Compiler Generator'', 1970, https://archive.org/details/compilergenerato00mcke</ref>{{discuss|editorial option in lieu of source}}
Popularised by [[Richard Stallman]], the layout may be influenced by his background of writing [[Lisp (programming language)|Lisp]] code.<ref name="gnu.org-lisp">{{cite web |url=https://www.gnu.org/gnu/rms-lisp.html |title=My Lisp Experiences and the Development of GNU Emacs (Transcript of speech at the International Lisp Conference) |first=Richard |last=Stallman |date=28 October 2002 |access-date=6 June 2016}}</ref> 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.<ref>{{cite book |last1=Baumann |first1=Richard |author-link1=:de:Richard Baumann (Mathematiker) |last2=Feliciano |first2=Manuel<!--, Jr.? --> |last3=Bauer |first3=Friedrich Ludwig |author-link3=Friedrich Ludwig Bauer |last4=Samelson |first4=Klaus |author-link4=Klaus Samelson |date=1964 |title=Introduction to ALGOL – A primer for the non-specialist, emphasizing the practical uses of the algorithmic language |series=Series in Automatic Computation |publisher=[[Prentice-Hall, Inc.]] |publication-place=Englewood Cliffs, New Jersey, USA |isbn=0-13-477828-6 |lccn=64-10740 |id=ark:/13960/t6qz35p37 |url=https://archive.org/details/introductiontoal00baum |access-date=2022-10-23}}</ref><ref>W. M. McKeeman, J. J. Horning, and D. B. Wortman, ''A Compiler Generator'', 1970, https://archive.org/details/compilergenerato00mcke</ref>{{discuss|editorial option in lieu of source}}


Although not indentation per se, GNU coding style also includes a space after a function name {{endash}} before the left parenthesis of an argument list.
Although not indentation per se, GNU coding style also includes a space after a function name {{endash}} before the left parenthesis of an argument list.<ref name="gnu.org"/>


<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
Line 431: Line 438:
final_thing ();
final_thing ();
}
}
</syntaxhighlight><ref name="gnu.org"/>
</syntaxhighlight>


This style combines the advantages of [[#Allman style|Allman]] and [[#Whitesmiths style|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.
This style combines the advantages of [[#Allman style|Allman]] and [[#Whitesmiths|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|date=February 2013}}
The [[GNU Coding Standards]] recommend this style, and nearly all maintainers of [[GNU project]] software use it.{{Citation needed|date=February 2013}}
Line 439: Line 446:
The [[GNU Emacs]] text editor and the GNU systems' [[indent (Unix)|indent]] command will reformat code according to this style by default.<ref>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 <code>emacs --no-init-file</code>.</ref> 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.
The [[GNU Emacs]] text editor and the GNU systems' [[indent (Unix)|indent]] command will reformat code according to this style by default.<ref>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 <code>emacs --no-init-file</code>.</ref> 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.<ref name="mcconnell" >{{cite book |title=Code Complete: A practical handbook of software construction |url=https://archive.org/details/codecomplete0000mcco |url-access=registration |last=McConnell |first=Steve |publisher=Microsoft Press |year=2004 |isbn=978-0-7356-1967-8 |location=Redmond, WA |pages=[https://archive.org/details/codecomplete0000mcco/page/746 746–747] |author-link=Steve McConnell}}</ref> 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".<ref>{{cite web |title=Linux kernel coding style |url=https://www.kernel.org/doc/Documentation/process/coding-style.rst |access-date=1 January 2017}}</ref>
[[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.<ref name="mcconnell" >{{cite book |title=Code Complete: A practical handbook of software construction |url=https://archive.org/details/codecomplete0000mcco |url-access=registration |last=McConnell |first=Steve |publisher=Microsoft Press |year=2004 |isbn=978-0-7356-1967-8 |location=Redmond, WA |pages=[https://archive.org/details/codecomplete0000mcco/page/746 746–747] |author-link=Steve McConnell}}</ref> The [[Linux kernel]] coding style documentation also recommends against this style, urging readers to burn a copy of the GNU coding standards as a "great symbolic gesture".<ref>{{cite web |title=Linux kernel coding style |url=https://www.kernel.org/doc/Documentation/process/coding-style.rst |access-date=1 January 2017}}</ref>


===Horstmann style===
=== Horstmann ===
The 1997 edition of ''Computing Concepts with C++ Essentials'' by Cay S. Horstmann adapts [[#Allman style|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''.<ref>{{cite book |first1=Kathleen |last1=Jensen |first2=Niklaus |last2=Wirth |title=PASCAL User Manual and Report |publisher=Springer-Verlag |year=1974}}</ref>
The 1997 edition of ''Computing Concepts with C++ Essentials'' by Cay S. Horstmann adapts [[#Allman style|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''.<ref>{{cite book |first1=Kathleen |last1=Jensen |first2=Niklaus |last2=Wirth |title=PASCAL User Manual and Report |publisher=Springer-Verlag |year=1974}}</ref>


Line 463: Line 470:
This style combines the advantages of [[#Allman style|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.<ref>[http://www.horstmann.com/bigcpp/styleguide.html Horstmann Style Guide]</ref>
This style combines the advantages of [[#Allman style|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.<ref>[http://www.horstmann.com/bigcpp/styleguide.html Horstmann Style Guide]</ref>


===Pico style===
=== Pico ===
This is the style used most commonly in the language [[Pico (programming language)|Pico]] by its designers. Pico lacks return statements, and uses semicolons as statement separators instead of terminators. It yields this syntax:<ref>{{Cite book|last=Ohno|first=Asako|title=2013 IEEE Frontiers in Education Conference (FIE) |chapter=A methodology to teach exemplary coding style considering students' coding style feature contains fluctuations |date=2013|pages=1908–1910|doi=10.1109/fie.2013.6685167|isbn=9781467352611 |s2cid=28385526}}</ref>
This is the style used most commonly in the language [[Pico (programming language)|Pico]] by its designers. Pico lacks return statements, and uses semicolons as statement separators instead of terminators. It yields this syntax:<ref>{{Cite book|last=Ohno|first=Asako|title=2013 IEEE Frontiers in Education Conference (FIE) |chapter=A methodology to teach exemplary coding style considering students' coding style feature contains fluctuations |date=2013|pages=1908–1910|doi=10.1109/fie.2013.6685167|isbn=9781467352611 |s2cid=28385526}}</ref>


Line 476: Line 483:
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.
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===
=== Ratliff ===
In the book ''Programmers at Work'',
In the book ''Programmers at Work'',
<ref name=lammers>{{cite book |last=Lammers |first=Susan |title=Programmers at Work |year=1986 |publisher=Microsoft Press |isbn=978-0-914845-71-3 |url-access=registration |url=https://archive.org/details/programmersatwor00lamm_0 }}</ref>
<ref name=lammers>{{cite book |last=Lammers |first=Susan |title=Programmers at Work |year=1986 |publisher=Microsoft Press |isbn=978-0-914845-71-3 |url-access=registration |url=https://archive.org/details/programmersatwor00lamm_0 }}</ref>
Line 482: Line 489:
the original programmer behind the popular [[dBase]]-II and -III [[fourth-generation programming language]]s,
the original programmer behind the popular [[dBase]]-II and -III [[fourth-generation programming language]]s,
discussed a style that is like 1TBS but the closing brace lines up with the indentation of the nested block.
discussed a style that is like 1TBS but the closing brace lines up with the indentation of the nested block.
He indicated that the style was originally documented in material from [[Digital Research]] Inc. This style has sometimes been termed ''banner'' style,<ref name=pattee>{{cite web |last1=Pattee |first1=Jim |title=Artistic Style 2.05 Documentation |url=http://astyle.sourceforge.net/astyle.html |website=Artistic Style |access-date=24 April 2015}}</ref> possibly for the resemblance to a banner hanging from a pole. In this style, which is to [[#Whitesmiths style|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)<ref name="mcconnell" /> 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''.<ref>{{cite book |first1=Brian W. |last1=Kernighan |first2=P. J. |last2=Plauger |title=Software Tools |url=https://archive.org/details/softwaretools00kern |url-access=registration |publisher=Addison-Wesley |year=1976|isbn=9780201036695 }}</ref>
He indicated that the style was originally documented in material from [[Digital Research]] Inc. This style has sometimes been termed ''banner'' style,<ref name=pattee>{{cite web |last1=Pattee |first1=Jim |title=Artistic Style 2.05 Documentation |url=http://astyle.sourceforge.net/astyle.html |website=Artistic Style |access-date=24 April 2015}}</ref> possibly for the resemblance to a banner hanging from a pole. In this style, which is to [[#Whitesmiths|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)<ref name="mcconnell" /> 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''.<ref>{{cite book |first1=Brian W. |last1=Kernighan |first2=P. J. |last2=Plauger |title=Software Tools |url=https://archive.org/details/softwaretools00kern |url-access=registration |publisher=Addison-Wesley |year=1976|isbn=9780201036695 }}</ref>


<syntaxhighlight lang=c>
<syntaxhighlight lang=c>
Line 504: Line 511:
=== Lisp style ===
=== Lisp style ===


While [[#GNU style|GNU style]] is sometimes characterized 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.
While [[#GNU|GNU style]] is sometimes characterized 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.
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.
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.


Line 566: Line 573:
[[APL (programming language)|APL]] style C resembles the terse style of APL code, and is commonly used in their implementations.<ref>{{cite web |url=https://www.jsoftware.com/ioj/iojATW.htm |title=The J Incunabulum |access-date=19 May 2022 |website=jsoftware.com}}</ref> This style was pioneered by [[Arthur Whitney (computer scientist)|Arthur Whitney]], and is heavily used in the implementation of [[K (programming language)|K]], Arthur's own project. The [[J (programming language)|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.
[[APL (programming language)|APL]] style C resembles the terse style of APL code, and is commonly used in their implementations.<ref>{{cite web |url=https://www.jsoftware.com/ioj/iojATW.htm |title=The J Incunabulum |access-date=19 May 2022 |website=jsoftware.com}}</ref> This style was pioneered by [[Arthur Whitney (computer scientist)|Arthur Whitney]], and is heavily used in the implementation of [[K (programming language)|K]], Arthur's own project. The [[J (programming language)|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.
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.{{cn|date=March 2024}}


=== Python style ===
=== Python style ===
Line 581: Line 588:
</syntaxhighlight>
</syntaxhighlight>


Conventionally, indentation is four spaces. Tabs are also possible.<ref name="pep8">{{cite web |author1=Guido van Rossum |author2=Barry Warsaw |author3=Alyssa Coghlan |author1-link=Guido van Rossum |title=PEP 8 – Style Guide for Python Code § Code Lay-out |url=https://peps.python.org/pep-0008/#code-lay-out |website=peps.python.org |access-date=11 March 2024 |language=en}}</ref>
Conventionally, indentation is four spaces. Tabs are also possible.<ref name="pep8">{{cite web |first1=Guido |last1=van Rossum |first2=Barry |last2=Warsaw |first3=Alyssa |last3=Coghlan |author1-link=Guido van Rossum |title=PEP 8 – Style Guide for Python Code § Code Lay-out |url=https://peps.python.org/pep-0008/#code-lay-out |website=[[Python Enhancement Proposal|peps.python.org]] |access-date=11 March 2024 |language=en}}</ref>


== Indentation size ==
== Indentation size ==
Line 606: Line 613:


== Style automation ==
== Style automation ==
{{uncited section|date=March 2024}}


A tool can automate formatting code per an indentation style, for example the [[Unix]] <code>[[indent (Unix)|indent]]</code> command.
A tool can automate formatting code per an indentation style, for example the [[Unix]] <code>[[indent (Unix)|indent]]</code> command.
Line 614: Line 622:


== Losing track of blocks ==
== Losing track of blocks ==
{{more citations needed|section|date=March 2024}}


In more complicated code, the programmer may lose track of block boundaries while reading the code.
In more complicated code, the programmer may lose track of block boundaries while reading the code.
Line 626: Line 635:


Some text editors allow the programmer to jump between the two corresponding braces of a block.
Some text editors allow the programmer to jump between the two corresponding braces of a block.
For example, [[Vi (text editor)|vi]] jumps to the brace that is for the same block as the one under the cursor when press the <code>%</code> key.
For example, [[Vi (text editor)|vi]] jumps to the brace enclosing the same block as the one under the cursor when pressing the <code>%</code> key.
Since the text cursor's <code>next</code> key (viz., the <code>n</code> key) retained directional positioning information (whether the <code>up</code> or <code>down</code> key was formerly pressed), the [[Macro (computer science)#Keyboard and mouse macros|dot macro]] (the <code>.</code> key) could then be used to place the text cursor on the next brace,<ref>{{cite book |first=Linda |last=Lamb |title=Learning the vi editor |year=1998 |url=https://archive.org/details/learningvieditor00lamb |url-access=registration |publisher=O'Reilly|isbn=9781565924260 }}</ref> given a suitable coding style. Instead, inspecting the block boundaries using the <code>%</code> key can be used to enforce a coding standard.
Since the text cursor's <code>next</code> key (viz., the <code>n</code> key) retained directional positioning information (whether the <code>up</code> or <code>down</code> key was formerly pressed), the [[Macro (computer science)#Keyboard and mouse macros|dot macro]] (the <code>.</code> key) could then be used to place the text cursor on the next brace,<ref>{{cite book |first=Linda |last=Lamb |title=Learning the vi editor |year=1998 |url=https://archive.org/details/learningvieditor00lamb |url-access=registration |publisher=O'Reilly|isbn=9781565924260 }}</ref> given a suitable coding style. Instead, inspecting the block boundaries using the <code>%</code> key can be used to enforce a coding standard.


Line 648: Line 657:


== Statement insertion ==
== Statement insertion ==
{{uncited section|date=March 2024}}


The K&R style prevents the common error caused by inserting a line of code after a control statement {{endash}} before the open brace. The inserted line causes the block to become disassociated from the control statement.
The K&R style prevents the common error caused by inserting a line of code after a control statement {{endash}} before the open brace. The inserted line causes the block to become disassociated from the control statement.
Line 695: Line 705:
* [[Secondary notation]]
* [[Secondary notation]]
* [[Syntax highlighting]]
* [[Syntax highlighting]]
* [[Indentation (typesetting)#Indentation in programming|Indentation in programming]]
* {{slink|Indentation (typesetting)#Indentation in programming}}
* ''[[Silicon Valley (season 3)|Bachmanity Insanity]]'', a ''[[Silicon Valley (TV series)|Silicon Valley]]'' episode featuring the topic
* ''[[Silicon Valley (season 3)|Bachmanity Insanity]]'', a ''[[Silicon Valley (TV series)|Silicon Valley]]'' episode featuring the topic
* [[Source-code formatter]]
* [[Source-code formatter]]

Revision as of 19:12, 13 July 2024

In computer programming, indentation style is a convention, a.k.a. style, governing the indentation of blocks of source code. An indentation style generally involves consistent width of whitespace (indentation size) before each line of a block, so that the lines of code appear to be related, and dictates whether to use space or tab characters for the indentation whitespace.

Overview

This article primarily addresses styles for free-form programming languages. As the name implies, such language code need not follow an indentation style. Indentation is a secondary notation that is often intended to lower cognitive load for a programmer to understand the structure of the code. Indentation can clarify the separation between the code executed based on control flow.

Structured 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 language processor (such as compiler or interpreter). A programmer must conform to the language's indentation rules although may be free to choose indentation size.

This article focuses on curly-bracket languages (that delimit blocks with curly brackets, a.k.a. curly braces, a.k.a. braces) and in particular C-family languages, but a convention used for one language can be adapted to another language. For example, a language that uses BEGIN and END keywords instead of braces can be adapted by treating BEGIN the same as the open brace and so on.

Indentation style only applies to text-based languages. Visual programming languages have no indentation.

Research

Despite the ubiquitous use of indentation styles, little research has been conducted on its value. First experiments, conducted by Weissman in 1974, did not show any effect.[1] In 2023, an experiment by Morzeck et al.[2] showed significant positive effect for nested if statements where non-indented code required on average 179% more time to read than indented code.

Notable styles

The table below includes code examples of various indentation styles. For consistency, indentation size for example code is 4 spaces even though this varies by coding convention.

Example Name
while (x == y)
{
    foo();
    bar();
}
Allman
while (x == y)
  {
    foo();
    bar();
  }
GNU
while (x == y)
    {
    foo();
    bar();
    }
Whitesmiths
while (x == y) {
    foo();
    bar();
}
K&R
while (x == y) {
    foo();
    bar();
    }
Ratliff
while (x == y)
{   foo();
    bar();
}
Horstmann
while (x == y)
{   foo();
    bar(); }
Pico
while (x == y)
  { foo();
    bar(); }
Lisp
#define W(c,b) {while(c){b}}
W(x==y,s();se();)
APL
while x == y:
    foo()
    bar()
Python

C/C++ styles

Attributes of C, C++ and other curly-brace programming language coding style include but are not limited to:

  • Placement of braces relative to other code elements
  • Use of tabs or spaces
  • Wrapping single-statement blocks in braces. Advocates cite the advantage that resulting code is safer since inserting a statement cannot result in control flow that disagrees with indentation. A cited disadvantage is that the code is longer since one line is needed for the closing brace of a block (except for the else if construct and a do{}while block).

K&R

The Kernighan & Ritchie (K&R) style is commonly used for C and C++ code and is the basis for many derivative styles. It is 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.

Although The C Programming Language does not explicitly define this style, it follows it consistently. 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 this style, a function has its opening and closing braces on their own lines and with the same indentation as the declaration, and with statements indented an additional level than the declaration. A multi-statement block inside a function, however, has its opening brace on the same line as its control clause while the closing brace remains on its own line unless followed by a keyword such as else or while.

Example code:

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();
}

Egyptian braces

The non-aligned braces of the multi-line blocks are nicknamed "Egyptian braces" (or "Egyptian brackets") for their resemblance to arms in some fanciful poses of ancient Egyptians.[3][4][5]

Single statements

A single-statement block does not have braces, which is a cause of easy-to-miss bugs such as the goto fail bug.

One True Brace

The One True Brace Style [6] (abbreviated 1TBS or OTBS[7]) is like the K&R style, but functions are formatted like multi-statement blocks with the opening brace on the same line as the declaration, and braces are not omitted for a single-statement block.[8]

bool is_negative(int x) {
    if (x < 0) {
        return true;
    } else {
        return false;
    }
}

Although not required by languages such as C/C++, using braces for single-statement blocks ensures that inserting a statement does not result in control flow that disagrees with indenting, as seen for example in Apple's infamous goto fail bug.

Cited advantages include shorter code (than K&R) since the starting brace needs no extra line, and the ending brace lines up with the statement it conceptually belongs to. One cost of this style is that the ending brace adds a line, which can be partly resolved in if/else blocks and do/while blocks.

Sources disagree as to the meaning of One True Brace Style. Some say that it is the variation specified here,[8] while others say it is "hacker jargon" for K&R.[9]

Linux kernel

The Linux kernel source tree is styled in a variant of K&R.[10] Linus Torvalds advises contributors to follow it. Attributes include:

  • Uses tab characters for indentation (not spaces) and assumes tab stops every 8 spaces
  • Brace layout matches K&R with open and close on their own lines and multi-statement open on same line as the control clause, separated by a space
  • Labels in a switch statement are aligned with the enclosing block (there is only one level of indents)
  • Maximum line length is 100 characters although the pre-2020 limit of 80 characters is preferred.[11]
  • A single-statement body of a compound statement (such as if, while, and do-while) does not need to 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 in braces:
int power(int x, int y)
{
        int result;

        if (y < 0) {
                result = 0;
        } else {
                result = 1;
                while (y-- > 0)
                        result *= x;
        }
        return result;
}

Java

A significant body of Java code uses a 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[12][13][14] 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.

Stroustrup

Bjarne Stroustrup adapted the K&R style for C++ in his books, such as Programming: Principles and Practice using C++ and The C++ Programming Language.[15]

Unlike the variants above, Stroustrup does not use a "cuddled else". Thus, Stroustrup would write[15]

    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:
        // construct a Vector
        Vector(int s) :elem(new double[s]), sz(s) { }
        // element access: subscripting
        double& operator[](int i) { return elem[i]; }
        int size() { return sz; }
    private:
        // pointer to the elements
        double * elem;
        // number of elements
        int sz;
    };

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.[16]

BSD KNF

The Berkeley Software Distribution (BSD) operating systems uses a style that is sometimes termed Kernel Normal Form (KNF). 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.[17]

The SunOS kernel and userland uses a similar indentation style.[17] Like KNF, this also was based on AT&T style documents and is sometimes termed Bill Joy Normal Form.[18] 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.[17][18][19]

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.

Examples:

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

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.[9]

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

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, were claimed to have been the most common bracing styles in 1991 by the Jargon File, with roughly equal popularity at the time.[9][20]

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.[21]

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

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.[22] 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.[23] 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.[24][25][discuss]

Although not indentation per se, GNU coding style also includes a space after a function name – before the left parenthesis of an argument list.[22]

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.[26] 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.[21] The Linux kernel coding style documentation also recommends against this style, urging readers to burn a copy of the GNU coding standards as a "great symbolic gesture".[27]

Horstmann

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.[28]

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.[29]

Pico

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:[30]

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

In the book Programmers at Work, [31] C. Wayne Ratliff, the original programmer behind the popular dBase-II and -III fourth-generation programming languages, discussed a style that is like 1TBS but the closing brace lines up with the indentation of the nested block. He indicated that the style was originally documented in material from Digital Research Inc. This style has sometimes been termed banner style,[32] 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)[21] 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.[33]

 // In C
 for (i = 0; i < 10; i++) {
     if (i % 2 == 0) {
         do_something(i);
         }
     else {
         do_something_else(i);
         }
     }

C derived language styles

The following styles are common for various languages derived from C that are both significantly similar and dissimilar. And, they can be adapted to C as well. They might be applied to C code written as part of a project mostly written in one of these other languages, where maintaining a consistent look and feel to the project's core code overrides considerations of using more conventional C style.

Lisp style

While GNU style is sometimes characterized 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. 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).

// C
for (i = 0; i < 10; i++)
    {if (i % 2 == 0)
        {do_something(i);}
     else
        {do_something_else(i);
         do_third_thing(i);}}

 

;; 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. [34] 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.[35] If code following the keywords where, let, or of omits braces and semicolons, then indentation is significant.[36]

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.[37] 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.[citation needed]

Python style

Python does not use braces. The indentation defines the blocks in what is called the off-side rule.

for i in range(10):
    if i % 2 == 0:
        do_something(i)
    else:
        do_something_else(i)
        do_third_thing(i)

Conventionally, indentation is four spaces. Tabs are also possible.[38]

Indentation size

Typically, programmers use the same width of whitespace to indent each block of code with commonly used widths varying from 1 to 4 spaces.

An experiment performed on PASCAL code in 1983, found that indentation size significantly affected comprehensibility. Indentation sizes between 2 and 4 characters proved optimal.[39] For Ruby, many shell scripting languages, and some forms of HTML formatting, two spaces per indentation level is generally used.[citation needed]

Although they both affect the general layout of code, indentation size is independent of the indentation style discussed here.

Tab vs. space

Typically, a programmer uses a text editor that provides tab stops at fixed intervals (a number of spaces), to assist in maintaining whitespace according to a style. The interval is called the tab width. Sometimes the programmer stores the code with tab characters – one for each tab key press or they store a sequence of spaces equal in number to the tab width.

Storing tab characters in code can cause visual misalignment when viewed in different contexts, which counters the value of the indentation style.

Programmers lack consensus on storing tab characters. Proponents of storing tab characters cite ease of typing and smaller text files since a single tab character serves the purpose of multiple spaces. Opponents, such as Jamie Zawinski, state that using spaces instead increases cross-platform portability. [40] Others, such as the writers of the WordPress coding standards, state the opposite: that hard tabs increase portability.[41] A survey of the top 400,000 repositories on GitHub found that spaces are more common.[42]

Many text editors, including Notepad++, TextEdit, Emacs, vi, and nano, can be configured to either store tab characters when entered via the tab key or to convert them to spaces (based on the configured tab width) so that tab characters are not added to the file when the tab key is pressed. Some editors can convert tab to space characters and vice versa.

Some text file pagers, such as less, can be configured for a tab width. Some tools such as expand/unexpand can convert on the fly via filters.

Style automation

A tool can automate formatting code per an indentation style, for example the Unix indent command.

Emacs provides commands to modify indentation, including hitting Tab on a given line. M-x indent-region indents code.

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.

Losing track of blocks

In more complicated code, the programmer may lose track of block boundaries while reading the code. This is often experienced in large sections of code containing many compound statements nested to many levels of indentation. As the programmer scrolls to the bottom of a huge set of nested statements, they may lose track of context – such as the control structure at the top of the block.

Long compound statements can be a code smell of over complexity which can be solved by refactoring.

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.

Some text editors allow the programmer to jump between the two corresponding braces of a block. For example, vi jumps to the brace enclosing the same block as the one under the cursor when pressing the % key. 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,[43] given a suitable coding style. Instead, inspecting the block boundaries using the % key can be used to enforce a coding standard.

Another way to maintain block awareness, is to use comments after the closing brace. For example:

for (int i = 0; i < total; i++) {
    foo();
} //for (i)
if (x < 0) {
   bar();
} //if (x < 0)

A disadvantage is maintaining the same code in multiple locations – above and below the block.

Some editors provide support for maintaining block awareness. A folding editor can hide (fold) and reveal (unfold) blocks by indentation level. Some editors highlight matching braces when the cursor is positioned next to one.

Statement insertion

The K&R style prevents the common error caused by inserting a line of code after a control statement – before the open brace. The inserted line causes the block to become disassociated from the control statement.

Given this starting code:

for (int i = 0; i < 10; i++)
{
    do_something();
} //for (i)

do_something will be called 10 times. Then, it is modified by adding a new second line:

for (int i = 0; i < 10; i++)
    do_something_else();
{
    do_something(); // called once!
} //for (i)

The original block (lines 3-5) is no longer the body of thefor loop and executes only once. Further, the comment on line 5 becomes wrong.

K&R style avoids this problem by keeping the control statement and the opening brace on the same line.

Original:

for (int i = 0; i < 10; i++) {
    do_something();
} //for (i)

Adding a new second line does not affect how many times do_something is called or the validity of the end comment.

for (int i = 0; i < 10; i++) {
    do_something_else();
    do_something();
} //for (i)

See also

References

  1. ^ Weissman, Laurence Mark (1974). A Methodology For Studying The Psychological Complexity of Computer Programs. CSRG-37 (Technical report). Computer Systems Research Group, University of Toronto. OCLC 1085612768. technicalreportc37univ – via Internet Archive.
  2. ^ Morzeck, Johannes; Hanenberg, Stefan; Werger, Ole; Gruhn, Volker (2023). Indentation in Source Code: A Randomized Control Trial on the Readability of Control Flows in Java Code with Large Effects. Proceedings of the 18th International Conference on Software Technologies - ICSOFT. Rome, Italy. pp. 117–128. doi:10.5220/0012087500003538. ISBN 978-989-758-665-1 – via Stefan Hanenberg on Google Drive (preprint).
  3. ^ "Java Style Guide". Archived from the original on 12 July 2018. Using either "Egyptian" curly braces or C-style curly braces is acceptable
  4. ^ "Egyptian brackets". Foldoc. A humourous [sic] term for K&R indent style, referring to the "one hand up in front, one down behind" pose
  5. ^ "Google JavaScript Style Guide". Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs
  6. ^ Darwin, Ian F. (1988). Checking C programs with Lint. California: O'Reilly and Assosciates. p. 51. ISBN 9780937175309.
  7. ^ "1TBS".
  8. ^ a b "Brace styles and JavaScript". 7 January 2013. Retrieved 8 November 2018.
  9. ^ a b c "The Jargon File". 4.4.7. 29 December 2003. Retrieved 18 August 2014.
  10. ^ A detailed description of the style is given at kernel.org.
  11. ^ Larabel, Michael. "The Linux Kernel Deprecates The 80 Character Line Coding Style". Phoronix. Phoronix Media. Retrieved 1 May 2022.
  12. ^ 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.
  13. ^ "Java Code Conventions" (PDF). Sun Microsystems. 12 September 1997. Archived from the original (PDF) on 13 May 2008. Retrieved 30 May 2008.
  14. ^ "Code Conventions for the Java Programming Language". Sun Microsystems. 20 March 1997. Retrieved 30 May 2008.
  15. ^ a b Stroustrup, Bjarne (September 2010). "PPP Style Guide" (PDF).
  16. ^ Stroustrup, Bjarne. "C++ Core Guidelines". GitHub. Retrieved 3 November 2018.
  17. ^ 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.
  18. ^ a b Gregg, Brendan. "DTraceToolkit Style Guide". Retrieved 6 February 2015.
  19. ^ Shannon, Bill (9 September 1998). "cstyle.pl". illumos-gate. 1.58. Sun Microsystems, Inc. Retrieved 6 February 2015.
  20. ^ "The Jargon File (Version 2.4.3)". 2.4.3. 23 January 1991. Retrieved 14 May 2024.
  21. ^ 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.
  22. ^ a b "Formatting Your Source Code". GNU Coding Standards. Retrieved 6 June 2016.
  23. ^ 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.
  24. ^ 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.
  25. ^ W. M. McKeeman, J. J. Horning, and D. B. Wortman, A Compiler Generator, 1970, https://archive.org/details/compilergenerato00mcke
  26. ^ 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.
  27. ^ "Linux kernel coding style". Retrieved 1 January 2017.
  28. ^ Jensen, Kathleen; Wirth, Niklaus (1974). PASCAL User Manual and Report. Springer-Verlag.
  29. ^ Horstmann Style Guide
  30. ^ 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.
  31. ^ Lammers, Susan (1986). Programmers at Work. Microsoft Press. ISBN 978-0-914845-71-3.
  32. ^ Pattee, Jim. "Artistic Style 2.05 Documentation". Artistic Style. Retrieved 24 April 2015.
  33. ^ Kernighan, Brian W.; Plauger, P. J. (1976). Software Tools. Addison-Wesley. ISBN 9780201036695.
  34. ^ "The Haskell 98 Report". haskell.org. Retrieved 3 March 2016.
  35. ^ Lipovača, Miran. "Making Our Own Types and Typeclasses". learnyouahaskell.com. Retrieved 3 February 2016.
  36. ^ Haskell Report 1.2 (1992), p.131 B.4 "Layout"
  37. ^ "The J Incunabulum". jsoftware.com. Retrieved 19 May 2022.
  38. ^ van Rossum, Guido; Warsaw, Barry; Coghlan, Alyssa. "PEP 8 – Style Guide for Python Code § Code Lay-out". peps.python.org. Retrieved 11 March 2024.
  39. ^ 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.
  40. ^ Zawinski, Jamie (2000). "Tabs versus Spaces: An Eternal Holy War". Retrieved 6 June 2016.
  41. ^ "WordPress Coding Standards". Retrieved 6 June 2016.
  42. ^ Hoffa, Felipe (26 July 2017). "400,000 GitHub repositories, 1 billion files, 14 terabytes of code: Spaces or Tabs?". Medium. Retrieved 9 July 2019.
  43. ^ Lamb, Linda (1998). Learning the vi editor. O'Reilly. ISBN 9781565924260.

Tabs and spaces