Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Indentation style
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Computer programming convention}} {{broader|Indentation (typesetting)}} {{Use dmy dates|date=October 2022}} In [[computer programming]], '''indentation style''' is a [[Convention (norm)|convention]] or [[programming style|style]], governing the [[Indentation (typesetting)|indentation]] of lines of [[source code]]. An indentation style generally specifies a consistent number of [[whitespace character]]s before each line of a block, so that the lines of code appear to be related, and dictates whether to use [[Space (punctuation)|spaces]] or [[Tab character|tabs]] as the indentation character. == Overview == 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]]. 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. 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 [[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. == 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 a significant positive effect for nested <code>if</code> statements where non-indented code required on average 179% more time to read than indented code. A follow up-experiment by Hanenberg et al.<ref>{{Cite journal |last1=Hanenberg |first1=Stefan |last2=Morzeck |first2=Johannes |last3=Gruhn |first3=Volker |date=2024-08-09 |title=Indentation and reading time: a randomized control trial on the differences between generated indented and non-indented if-statements |journal=Empirical Software Engineering |language=en |volume=29 |issue=5 |pages=134 |doi=10.1007/s10664-024-10531-y |issn=1573-7616|doi-access=free }}</ref> confirmed a large effect (although in that experiment non-indented code just took 113% more time to read) and revealed that the differences in reading times can be explained by the code that can be skipped (for indented code). In another experiment on JSON objects<ref>{{Cite book |last1=Hanenberg |first1=Stefan |last2=Morzeck |first2=Johannes |last3=Werger |first3=Ole |last4=Gries |first4=Stefan |last5=Gruhn |first5=Volker |chapter=Indentation and Reading Time: A Controlled Experiment on the Differences Between Generated Indented and Non-indented JSON Objects |series=Communications in Computer and Information Science |date=2024 |volume=2104 |editor-last=Fill |editor-first=Hans-Georg |editor2-last=Domínguez Mayo |editor2-first=Francisco José |editor3-last=van Sinderen |editor3-first=Marten |editor4-last=Maciaszek |editor4-first=Leszek A. |title=Software Technologies |chapter-url=https://link.springer.com/chapter/10.1007/978-3-031-61753-9_4 |language=en |location=Cham |publisher=Springer Nature Switzerland |pages=50–75 |doi=10.1007/978-3-031-61753-9_4 |isbn=978-3-031-61753-9}}</ref> non-indented code took even 544% more time to read. == 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. {| class="wikitable" ! Example !! Name |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#Allman style|Allman]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#GNU|GNU]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#Whitesmiths|Whitesmiths]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#K&R|K&R]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#Ratliff|Ratliff]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#Horstmann|Horstmann]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#Pico|Pico]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> while (x == y) { foo(); bar(); } </syntaxhighlight> | [[#Lisp style|Lisp]] |- | style="padding: 0 4px" | <syntaxhighlight lang=c> #define W(c,b) {while(c){b}} W(x==y,f();b();) </syntaxhighlight> | [[#APL style|APL]] |} == C/C++ styles == Attributes of [[C language|C]], [[C++]] and other [[curly-brace programming language]] coding style include but are not limited to: * 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 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]]''. Although ''[[The C Programming Language]]'' does not explicitly define this style, it follows it consistently. 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> In this style, a function has its opening and closing braces on their own lines and with the same indentation as the declaration, while the statements in the body of the function are indented an additional level. 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: <syntaxhighlight lang="c"> 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(); } </syntaxhighlight> ==== Egyptian braces ==== {{anchor|Egyptian}} 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 ==== 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]]. === One True Brace === {{anchor|Variant: 1TBS}} {{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> <syntaxhighlight lang="cpp"> bool is_negative(int x) { if (x < 0) { return true; } else { return false; } } </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]]. Cited advantages include shorter code (than K&R) since the starting brace needs no extra line, that the ending brace lines up with the statement it conceptually belongs to, and the perceived stylistic consistency of using the same brace style in both function bodies and multi-line statement blocks.<ref name="kernel.coding-style" /> 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> === 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 the braces of function definitions on their own lines and the opening brace of compound statements on the 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> int power(int x, int y) { int result; if (y < 0) { result = 0; } else { result = 1; while (y-- > 0) result *= x; } return result; } </syntaxhighlight> === Java === 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. 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 | title=Code Conventions for the Java Programming Language | publisher=Sun Microsystems | date=20 March 1997 | 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]]. === 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]]''.<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" /> <syntaxhighlight lang=c> if (x < 0) { puts("Negative"); negative(x); } else { puts("Non-negative"); nonnegative(x); } </syntaxhighlight> Stroustrup extends K&R style for classes, writing them as follows: <syntaxhighlight lang=cpp> 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; }; </syntaxhighlight> Stroustrup does not indent the labels {{code|public:}} and {{code|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''.<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> === 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 (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> In this style, the hard tabulator (ts in [[Vi (text editor)|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 <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: <syntaxhighlight lang=c> while (x == y) { something(); something_else(); } final_thing(); </syntaxhighlight> <syntaxhighlight lang=c> 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; } } </syntaxhighlight> <syntaxhighlight lang=c> static JSBool pgresult_constructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { QUEUE_EXCEPTION("PGresult class not user-instantiable"); return (JS_FALSE); } </syntaxhighlight> === Allman === {{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). 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> while (x == y) { something(); something_else(); } final_thing(); </syntaxhighlight> This style is similar to the standard indentation used by the [[Pascal (programming language)|Pascal]] languages and [[Transact-SQL]], where the braces are equivalent to the keywords <code>begin</code> and <code>end</code>. <syntaxhighlight lang=pascal> (* Example Allman code indentation style in Pascal *) procedure dosomething(x, y: Integer); begin while x = y do begin something(); something_else(); end; end; </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. For example, the following is still correct syntactically: <syntaxhighlight lang=c> // while (x == y) { something(); something_else(); } </syntaxhighlight> As is this: <syntaxhighlight lang=c> // for (int i=0; i < x; i++) // while (x == y) if (x == y) { something(); something_else(); } </syntaxhighlight> Even like this, with conditional compilation: <syntaxhighlight lang=c> int c; #ifdef HAS_GETCH while ((c = getch()) != EOF) #else while ((c = getchar()) != EOF) #endif { do_something(c); } </syntaxhighlight> ==== Variant: Allman-8 ==== 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 === 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]], 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. Like Ratliff style, the closing brace is indented the same as statements within the braces.<ref name="mcconnell" /> <syntaxhighlight lang=c> while (x == y) { something(); something_else(); } final_thing(); </syntaxhighlight> The advantages of this style are similar to those of the [[#Allman style|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: <syntaxhighlight lang=c> 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; } </syntaxhighlight> <code>else if</code> are treated as statement, much like the <code>#elif</code> preprocessor statement. === GNU === {{Main article|GNU coding standards}} 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 |title=Formatting Your Source Code |website=[[GNU Coding Standards]] |access-date=6 June 2016 }}</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 |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.<ref name="gnu.org"/> <syntaxhighlight lang=c> static char * concat (char *s1, char *s2) { while (x == y) { something (); something_else (); } final_thing (); } </syntaxhighlight> 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 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 recommends against this style, urging readers to burn a copy of the GNU coding standards as a "great symbolic gesture".<ref name="kernel.coding-style" >{{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 === 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> <syntaxhighlight lang=c> while (x == y) { something(); something_else(); //... if (x < 0) { printf("Negative"); negative(x); } else { printf("Non-negative"); nonnegative(x); } } final_thing(); </syntaxhighlight> 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 === 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> <!--no geshi support for pico--> <pre> stuff(n): { x: 3 * n; y: do_stuff(x); y + x } </pre> 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'', <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> C. Wayne Ratliff, 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. 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> // In C for (i = 0; i < 10; i++) { if (i % 2 == 0) { do_something(i); } else { do_something_else(i); } } </syntaxhighlight> == 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|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 [[Expression (computer science)|expression]]s, with no distinct class of [[Statement (computer science)|statement]]s; 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 <code>else</code> keyword in an <code>if : then | else</code> block, instead rendering it uniformly as <code>(if expr1 expr2 expr3)</code>. <syntaxhighlight lang="c"> // C for (i = 0; i < 10; i++) {if (i % 2 == 0) {do_something(i);} else {do_something_else(i); do_third_thing(i);}} </syntaxhighlight> <syntaxhighlight lang="lisp"> ;; Lisp (dotimes (i 10) (if (= (rem i 2) 0) (do-something i) (progn (do-something-else i) (do-third-thing i)))) </syntaxhighlight> <sup>Note: <code>progn</code> is a procedure for evaluating multiple sub-expressions sequentially for [[Side effect (computer science)|effects]], while discarding all but the final (nth) return value. If all return values are desired, the <code>values</code> procedure would be used.</sup> === Haskell style === [[Haskell (programming language)|Haskell]] layout can make the placement of braces optional, although braces and semicolons are allowed in the language. <ref>{{cite web |url=https://www.haskell.org/onlinereport/lexemes.html |title=The Haskell 98 Report |access-date=3 March 2016 |website=haskell.org}}</ref> The two segments below are equally acceptable to the compiler: <syntaxhighlight lang=haskell> 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 } </syntaxhighlight> In Haskell, layout can replace braces. Usually the braces and semicolons are omitted for [[Procedural programming|procedural]] <code>do</code> 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.<ref>{{cite web |url=http://learnyouahaskell.com/making-our-own-types-and-typeclasses |title=Making Our Own Types and Typeclasses |access-date=3 February 2016 |website=learnyouahaskell.com |last=Lipovača |first=Miran}}</ref> If code following the keywords <code>where</code>, <code>let</code>, or <code>of</code> omits braces and semicolons, then indentation is significant.<ref>Haskell Report 1.2 (1992), p.131 B.4 "Layout"</ref> === APL style === For an example of how terse APL typically is, here is the implementation of the step function for the Game of Life: <syntaxhighlight lang=apl> life←{⊃1⍵∨.∧3 4=+/+⌿¯1 0 1∘.⊖¯1 0 1⌽¨⊂⍵} </syntaxhighlight> [[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.<ref>{{cite web |url=https://github.com/jsoftware/jsource/tree/master/jsrc |title=The J source code |access-date=12 September 2024 |website=github.com}}</ref> == 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.<ref>{{cite journal |last1=Miara |first1=Richard J. |last2=Musselman |first2=Joyce A. |last3=Navarro |first3=Juan A. |last4=Shneiderman |first4=Ben |name-list-style=amp |date=November 1983 |title=Program Indentation and Comprehensibility |url=http://www.cs.umd.edu/~ben/papers/Miara1983Program.pdf |access-date=3 August 2017 |journal=Communications of the ACM |volume=26 |number=11 |pages=861–867 |doi=10.1145/182.358437|s2cid=11767796 }}</ref> 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 {{endash}} one for each tab key press or they store a sequence of spaces equal in number to the tab width. Storing [[tab character]]s 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]] [[Porting|portability]]. <ref>{{cite web |url=http://www.jwz.org/doc/tabs-vs-spaces.html |title=Tabs versus Spaces: An Eternal Holy War |first=Jamie |last=Zawinski |year=2000 |access-date=6 June 2016}}</ref> Others, such as the writers of the [[WordPress]] coding standards, state the opposite: that hard tabs increase portability.<ref>{{cite web |url=http://codex.wordpress.org/WordPress_Coding_Standards#Indentation |title=WordPress Coding Standards |access-date=6 June 2016}}</ref> A survey of the top 400,000 repositories on [[GitHub]] found that spaces are more common.<ref>{{cite web|url=https://medium.com/@hoffa/400-000-github-repositories-1-billion-files-14-terabytes-of-code-spaces-or-tabs-7cfe0b5dd7fd|title=400,000 GitHub repositories, 1 billion files, 14 terabytes of code: Spaces or Tabs?|last=Hoffa|first=Felipe|date=2017-07-26|website=Medium|language=en|access-date=2019-07-09}}</ref> Many text editors, including [[Notepad++]], [[TextEdit]], [[Emacs]], [[vi (text editor)|vi]], and [[GNU nano|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 [[Terminal pager|text file pagers]], such as [[Less (Unix)|less]], can be configured for a tab width. Some tools such as [[Expand (Unix)|expand]]/[[unexpand]] can convert on the fly via filters. == Style automation == {{unreferenced section|date=March 2024}} A tool can automate formatting code per an indentation style, for example the [[Unix]] <code>[[indent (Unix)|indent]]</code> command. [[Emacs]] provides commands to modify indentation, including hitting <code>Tab</code> on a given line. <code>M-x indent-region</code> 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 == {{more citations needed|section|date=March 2024}} 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 {{endash}} such as the control structure at the top of the block. Long compound statements can be a [[code smell]] of [[Cyclomatic complexity|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 flow|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 <code>[[for loop|for]]</code>, 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 (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. Another way to maintain block awareness, is to use comments after the closing brace. For example: <syntaxhighlight lang=c> for (int i = 0; i < total; i++) { foo(); } //for (i) </syntaxhighlight> <syntaxhighlight lang=c> if (x < 0) { bar(); } //if (x < 0) </syntaxhighlight> A disadvantage is maintaining the same code in multiple locations {{endash}} 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 (user interface)|cursor]] is positioned next to one. ==See also== * [[Secondary notation]] * [[Syntax highlighting]] * {{slink|Indentation (typesetting)#Indentation in programming}} * ''[[Silicon Valley (season 3)|Bachmanity Insanity]]'', a ''[[Silicon Valley (TV series)|Silicon Valley]]'' episode featuring the topic * [[Source-code formatter]] ==References== {{Reflist}} ==External links== * [http://syque.com/cstyle/index.htm ''C Style: Standards and Guidelines: Defining Programming Standards for Professional C Programmers''], Prentice Hall, {{ISBN|0-13-116898-3}} / {{ISBN|978-0-13-116898-5}} (full text is also online). Straker, David (1992). * [http://milan.adamovsky.com/2010/08/contextual-indent.html Contextual Indent] * [https://www.gnu.org/prep/standards/standards.html GNU Coding Standards] ===Tabs and spaces=== *[http://www.jwz.org/doc/tabs-vs-spaces.html ''Tabs versus Spaces: An Eternal Holy War''] by Jamie Zawinski *[http://adamspiers.org/computing/why_no_tabs.html ''Why I prefer no tabs in source code''] by Adam Spiers *[https://web.archive.org/web/20131209200846/http://derkarl.org/why_to_tabs.html ''Why I love having tabs in source code''] (archived) *[http://nickgravgaard.com/elastictabstops/ ''Elastic tabstops – the solution to the tabs-versus-spaces issue''] {{DEFAULTSORT:Indent Style}} [[Category:Software wars]] [[Category:Text editor features]] [[Category:Source code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Ambox
(
edit
)
Template:Anchor
(
edit
)
Template:Broader
(
edit
)
Template:Citation needed
(
edit
)
Template:Cite book
(
edit
)
Template:Cite conference
(
edit
)
Template:Cite journal
(
edit
)
Template:Cite news
(
edit
)
Template:Cite tech report
(
edit
)
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:Discuss
(
edit
)
Template:Endash
(
edit
)
Template:ISBN
(
edit
)
Template:Main article
(
edit
)
Template:More citations needed
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Slink
(
edit
)
Template:Unreferenced
(
edit
)
Template:Unreferenced section
(
edit
)
Template:Use dmy dates
(
edit
)