indentation style in computer programming an indentation style is a convention governing the indentation of blocks of code to convey program structure this article largely addresses the freeform languages such as c and its descendants but can be and often is applied to most other programming languages especially those in the curly bracket family where whitespace is otherwise insignificant indentation style is only one aspect of programming style indenting is not a requirement of most programming languages where it is used as secondary notation rather indenting helps better convey the structure of a program to human readers especially it is used to clarify the link between control flow constructs such as conditions or loops and code contained within and outside of them however some languages such as python and occam use indenting to determine the structure instead of using braces or keywords this is termed the offside rule in such languages indenting is meaningful to the compiler or interpreter it is more than only a clarity or style issue this article uses brackets to refer to what are termed parentheses in american english and braces to refer to what are termed curly brackets in american english brace placement in compound statements the main difference between indentation styles lies in the placing of the braces of the compound statement that often follows a control statement if while for the table below shows this placement for the style of statements discussed in this article function declaration style is another case the style for brace placement in statements may differ from the style for brace placement of a function definition for consistency the indentation depth has been kept constant at 4 spaces regardless of the preferred indentation depth of each style brace placement styles while x y something somethingelse kr aka 1tbs and variants stroustrup linux kernel bsd knf while x y something somethingelse allman while x y something somethingelse gnu while x y something somethingelse whitesmiths while x y something somethingelse horstmann while x y something somethingelse pico while x y something somethingelse ratliff while x y something somethingelse lisp tabs spaces and size of indentations many early programs used tab characters to indent for simplicity and to save on source file size unix editors generally view tabs as equaling eight characters while macintosh and windows environments would set them to four creating confusion when code was transferred between environments modern programming editors can now often set arbitrary indentation sizes and will insert the proper mix of tabs and spaces the issue of using hard tabs or spaces is an ongoing debate in the programming community some programmers such as jamie zawinski state that spaces instead of tabs increase crossplatform portability the size of the indentation is usually independent of the style in an experiment from 1983 performed on pascal code a significant influence of indentation size on comprehensibility was found the results indicate that indentation levels in the range from 2 to 4 characters ensure best comprehensibility tools there are many computer programs that automatically correct indentation styles according to the preferences of the program author and the length of indents associated with tabs a famous one is indent a program included with many unixlike operating systems in emacs various commands are available to automatically fix indenting problems including hitting tab on a given line in the default configuration mx indentregion can be used to properly indent large sections of code depending on the mode emacs can also replace leading indentation spaces with the proper number of tabs followed by spaces which results in the minimal number of characters for indenting each source line elastic tabstops is a tabulation style which requires support from the text editor where entire blocks of text are kept automatically aligned when the length of one line in the block changes styles kr style the kr style is commonly used in c c and other curly brace programming languages it was the style used in the original unix kernel kernighan and ritchies book the c programming language as well as kernighan and plaugers book the elements of programming style when following kr 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 the blocks inside a function however have their opening braces at the same line as their respective control statements closing braces remain in a line of their own unless followed by a keyword else or while such nonaligned braces are nicknamed egyptian braces or egyptian brackets for their resemblance to arms in some fanciful poses of ancient egyptians int mainint argc char argv while x y something somethingelse if someerror docorrect else continueasusual finalthing the c programming language does not explicitly specify this style though it is followed consistently throughout the book from the book the position of braces is less important although people hold passionate beliefs we have chosen one of several popular styles pick a style that suits you then use it consistently in old versions of the c language argument types needed to be declared on the subsequent line ie just after the header of the function original preiso c style without function prototypes int mainargc argv int argc char argv variant 1tbs otbs advocates of this style sometimes refer to it as the one true brace style abbreviated as 1tbs or otbs 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 singleline conditionals so that insertion of a new line of code anywhere is always safe ie such an insertion will not make the flow of execution disagree with the source code indenting 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 ifelse blocks and dowhile blocks void checknegativex if x 0 putsnegative else nonnegativex there are many mentions of the one true brace style out there but there is some confusion as to its true form some sources say it is the variation specified above variant linux kernel a minor variant of the kr style is the linux kernel style which is known for its extensive use in the source tree of the linux kernel linus torvalds strongly advises all contributors to follow it a detailed description of the style which considers indenting and naming conventions comments and various other aspects can be found at kernelorg the style borrows many elements from kr the kernel style uses tabs with tab stops set at 8 characters for indenting opening curly braces of a function go to the start of the line following the function header any other opening curly braces go on the same line as the corresponding statement separated by a space labels in a switch statement are aligned with the enclosing block there is only one level of indents a singlestatement body of a compound statement such as if while and dowhile need not be surrounded by curly braces if however one or more of the substatements in an ifelse statement require braces then both substatements should be wrapped inside curly braces line length is limited to 80 characters the linux kernel style specifies that if only one branch of a conditional statement is a single statement use braces in both branches int powerint x int y int result if y 0 result 0 else result 1 while y 0 result x return result variant mandatory braces some advocate mandatory braces for control statements with only a single statement in its scope ie bracing every if else while etc including singleline conditionals so that insertion of a new line of code anywhere is always safe ie such an insertion will not make the flow of execution disagree with the source code indenting the cost of this style is that one extra full line is needed for the last block except for intermedia blocks in ifelse ifelse constructs and dowhile blocks variant java while java is sometimes written in other styles a significant body of java code uses a minor variant of the kr 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 microsystemss original style guides used this kr variant and as a result most of the standard source code for the java api is written in this style it is also a popular indentation style for actionscript and javascript along with the allman style variant stroustrup stroustrup style is bjarne stroustrups adaptation of kr style for c as used in his books such as programming principles and practice using c and the c programming language unlike the variants above stroustrup does not use a cuddled else thus stroustrup would write if x 0 putsnegative negativex else putsnonnegative nonnegativex stroustrup extends kr style for classes writing them as follows class vector public vectorint s elemnew double szs construct a vector double operator element access subscripting int size return sz private double elem pointer to the elements int sz number of elements stroustrup does not indent the labels public and private also in this style while the opening brace of a function starts on a new line the opening brace of a class is on the same line as the class name stroustrup allows writing short functions all on one line stroustrup style is a named indentation style available in the editor emacs stroustrup encourages a krderived style layout with c as stated in his modern c core guidelines variant bsd knf also termed kernel normal form this is the form of most of the code used in the berkeley software distribution bsd operating systems although mostly intended for kernel code it is also widely used in userland code it is essentially a thoroughlydocumented variant of kr style as used in the bell labs version 6 7 unix source code the sunos kernel and userland uses a similar indenting style 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 toplevel block should also leave an empty line after their opening block brace here follow a few samples while x y something somethingelse finalthing if data null res 0 if jsdefinepropertycx o data stringtojsvaljsnewstringcopyncx data res null null jspropenumerate 0 queueexceptioninternal error goto err pqfreememdata else if jsdefinepropertycx o data objecttojsvalnull null null jspropenumerate 0 queueexceptioninternal error goto err static jsbool pgresultconstructorjscontext cx jsobject obj uintn argc jsval argv jsval rval queueexceptionpgresult class not userinstantiable return jsfalse allman style the allman style is named after eric allman it is also sometimes termed bsd style since allman wrote many of the utilities for bsd unix although this should not be confused with the different bsd knf style see above this style puts the brace associated with a control statement on the next line indented to the same level as the control statement statements within the braces are indented to the next level while x y something somethingelse finalthing this style is similar to the standard indenting used by the pascal languages and transactsql where the braces are equivalent to the keywords begin and end example allman code indenting style in pascal procedure dosomethingx y integer begin while x y do begin something somethingelse 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 outerfunction block for example the following is still correct syntactically while x y something somethingelse as is this for int i0 i x i while x y if x y something somethingelse even like this with conditional compilation int c ifdef hasgetch while c getch eof else while c getchar eof endif dosomethingc variant allman8 a popular variant for use in education whitesmiths style the whitesmiths style also sometimes termed wishart style was originally used in the documentation for the first commercial c compiler the whitesmiths compiler it was also popular in the early days of windows since it was used in three influential windows programming books programmers guide to windows by durant carlson yao programming windows by petzold and windows 30 power programming techniques by norton yao whitesmiths along with allman have been the most common bracing styles with equal popularity according to the jargon file 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 while x y something somethingelse finalthing 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 jsdefinepropertycx o data stringtojsvaljsnewstringcopyncx data res null null jspropenumerate queueexceptioninternal error goto err pqfreememdata else if jsdefinepropertycx o data objecttojsvalnull null null jspropenumerate queueexceptioninternal error goto err else if are treated as statement much like the elif preprocessor statement gnu style gnu coding standards 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 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 although not directly related to indenting gnu coding style also includes a space before the bracketed list of arguments to a function static char concat char s1 char s2 while x y something somethingelse finalthing 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 singlelevel indenting 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 the gnu emacs text editor and the gnu systems indent command will reformat code according to this style by default those who do not use gnu emacs or similarly extensiblecustomisable editors may find that the automatic indenting 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 horstmann style the 1997 edition of computing concepts with c essentials by cay s horstmann adapts allman by placing the first statement of a block on the same line as the opening brace this style is also used in examples in jensen and wirths pascal user manual and report while x y something somethingelse if x 0 printfnegative negativex else printfnonnegative nonnegativex finalthing 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 kr style however the 2003 edition now uses allman style throughout pico style this is the style used most commonly in the language pico by its designers pico lacks return statements and uses semicolons as statement separators instead of terminators it yields this syntax stuffn x 3 n y dostuffx y x the advantages and disadvantages are similar to those of saving screen real estate with kr 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 kr style where one brace shares space with a line of code and one brace has a line alone ratliff style in the book programmers at work in c for i 0 i 10 i if i 2 0 dosomethingi else dosomethingelsei or in a markup language table tr td lots of stuff more stuff td td alternative for short lines td td etc td tr table table tr etc table lisp style a programmer may even go as far as to insert closing braces in the last line of a block this style makes indenting the only way to distinguish blocks of code but has the advantage of containing no uninformative lines this could easily be called the lisp style because this style is very common in lisp code or the python style python has no braces but the layout is very similar as shown in the code blocks below in python layout is a part of the language called the offside rule in c for i 0 i 10 i if i 2 0 dosomethingi else dosomethingelsei dothirdthingi in python for i in range10 if i 2 0 dosomethingi else dosomethingelsei dothirdthingi in lisp dotimes i 10 if rem i 2 0 dosomething i progn dosomethingelse i dothirdthing i haskell style haskell layout can make the placement of braces optional although braces and semicolons are allowed in the language 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 indentation is significant and 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 other considerations losing track of blocks in some situations there is a risk of losing track of block boundaries this is often seen in large sections of code containing many compound statements nested to many levels of indentations by the time the programmer scrolls to the bottom of a huge set of nested statements he or she may have lost track of which control statements go where however overlylong code could have other causes such as being too complex and a programmer facing this problem might instead consider whether code refactoring would help in the longer term programmers who rely on counting the opening braces may have difficulty with indentation styles such as kr 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 kr because the blocks are shorter to avoid losing track of control statements such as for a large indentation can be used such as an 8unitwide hard tab along with breaking up large functions into smaller and more readable functions linux is done this way while using the kr style in text editors of the vi family one means to track block boundaries is to position the text cursor over one of the braces and press the key the cursor then jumps to the opposing brace since the text cursors 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 given a suitable coding style instead inspecting the block boundaries using the key can be used to enforce a coding standard another way is to use inline comments added after the closing brace for int i 0 i total i foobar for i if x 0 barfoo if x 0 the major disadvantage of this method is maintaining duplicate code in multiple locations another solution is implemented in a folding editor which can hide or reveal blocks of code via their indentation level or compoundstatement structure many editors will also highlight matching brackets or braces when the cursor is positioned next to one statement insertion kr style prevents another common error suffered when using the standard unix line editor ed a statement mistakenly inserted between the control statement and the opening brace of the loop block turns the body of the loop into a single trip for int i 0 i 10 i whoopsbar repeated 10 times with i from 0 to 9 onlyonce programmer intended this to be done 10 times for i this comment is no longer valid and is very misleading kr style avoids this problem by keeping the control statement and the opening brace on the same line secondary notation syntax highlighting indentation typesettingindentation in programming c style standards and guidelines defining programming standards for professional c programmers prentice hall isbn0131168983 isbn9780131168985 full text is also online straker david 1992 contextual indent gnu coding standards source code formatters at curlie 