It serves to keep the code easier to understand.
For example, see this code without any indentation:
if (a) {
if (b) {
while (c) {
d();
}
} else if (e) {
f();
} else if (g) {
h();
}
} else if (i) {
while (j) {
k();
}
}
Now look at the same code with a very bad indentation:
if (a) {
if (b)
{
while (c) {
d();
}
}
else
if (e)
{
f();
}
else if (g)
{
h();
}
} else
if (i) {
while (j) {
k();
}
}
And now the well-indented code:
if (a) {
if (b) {
while (c) {
d();
}
} else if (e) {
f();
} else if (g) {
h();
}
} else if (i) {
while (j) {
k();
}
}
Note that in nicely indented code, it's much easier to notice right away how the structures are nested. In the indentation - free code, what the human eye and brain sees is just a soup that opens and closes keys, if
s, while
s, etc and it 's hard to know where things start and where they end. In the badly-indented code, it's even worse, as there is an extra mental effort in realizing that the suggested indentation is inadequate and figuring out which one would be the right one.
Finally, it all boils down to making it easier to read the code to a human, not to a machine.
In particular, look at these terrible examples where the wrong indentation makes the instructions appear to be in the wrong place:
if (x)
y();
z();
if (a)
if (b)
c();
else
d();
if (x)
// y();
z();
In the first case, z()
seems to be within if
, but is out. In the second case, the else
is in% internal%, but was indented as if it were in the external. In the third case, since the if
line was commented out, y()
ended up hitching in z()
. These pathological cases are avoided if you always delimit the scope with braces (or the equivalent depending on the language) or use an indentation-sensitive language such as Python.
For the compiler, indentation almost always does not matter. The main exception is obviously Python, where the compiler uses indentation to nest structures. Another exception I remember is from Scheme / Racket, where although the compiler does not need the indentation when the code is correct, in case there is a compilation error it will use the indentation to suggest where is the most likely location of the error to have occurred .