Microsoft Store
 

Indent style


 

In computer programming, an indent style is a convention governing the indentation of blocks of code to convey the program's structure. This article largely addresses the C programming language and its descendants, but can be (and frequently is) applied to most other programming languages (especially those in the curly bracket family). Indent style is just one aspect of programming style.

K&R style

The K&R style, so-called because it was used in Kernighan and Ritchie's book The C Programming Language, is the traditional choice for C. It is less common for Objective C, C++, Java, C#, and others. It keeps the first opening brace on the same line as control statement, indents the statements within the braces, and puts the closing brace on the same indentation level as the control statement (on a line of its own).

Related Topics:
K&R - Kernighan - Ritchie's - The C Programming Language

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

while (x == y) {

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

something();

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

somethingelse();

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

}

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

finalthing();

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

People who prefer this style often refer to it as the "One True Brace Style" (abbreviation 1TBS). The source code of the UNIX kernel and Linux kernel is written in this style.

Related Topics:
UNIX - Kernel - Linux kernel

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

Proponents believe advantages of this style are that the ending brace lines up with the statement it conceptually belongs to; and the beginning brace does not occupy an entire line by itself. This keeps more code visible at once, which is a readability advantage. Some say that one disadvantage of this style is that the beginning brace can be more difficult to locate than with the BSD style, and the ending brace shares the disadvantage of the BSD style. The latter can be partially resolved in if/else blocks and do/while blocks:

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

if (x < 0) {

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

printf("Negative");

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

negative(x);

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

} else {

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

printf("Positive");

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

positive(x);

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

}

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

For other control statements, such as for, inline comments can be added after the brace::

Related Topics:
Control statements - For

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

for ( int i = 0 ; i < total ; i++ ) {

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

foo(bar);

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

} //for

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

if (x < 0) {

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

bar(foo);

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

} //if

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

For functions, which are special because they can not nest in C, the opening and closing braces get lines to themselves:

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

int main (int argc, char* argv)

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

// Do things

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

return 0;

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

}

~ ~ ~ ~ ~ ~ ~ ~ ~ ~