Serves to keep code easier to understand.
For example, look at 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 see the same code with a very badly indented:
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 well-indented code, it’s much easier to see straight away how the structures are nested. Already in the code without indentation, what the human eye and brain see is just a soup of open and close keys, if
s, while
s, etc and it gets hard to know where things start and where they end. In the poorly indented code, it’s even worse, because there’s an extra mental effort in realizing that the suggested indentation is inadequate and understanding which would be the correct one.
Anyway, it all comes down to making it easier for a human to read the code, not 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, the z()
seems to be inside the if
, but it’s out. In the second case, the else
is in the if
internal, but was indented as if it were in the external. In the third case, as the line of the y()
was commented, the z()
ended up hitchhiking inside the if
. These pathological cases are avoided if you always delimit the scope with keys (or the equivalent depending on the language) or use an indentation-sensitive language like Python.
For the compiler, indentation almost always doesn’t matter. The main exception is obviously Python, where the compiler uses indentation to nest the structures. Another exception I remember is Scheme/Racket, where although the compiler does not need the indentation when the code is correct, in case there is a build error it will use the indentation to suggest where is the most likely location of the error occurred.
22h of the night , you tired , deployment turn or something , ai need to analyze a code of a language that does not dominate much in a module of the system that has a poor knowledge , do not need to change only take a doubt , then you get a messy, unidentified code ...
– Motta
Note: Python indentation is required, yes.
– Woss
Yeah, but it’s indentation or indentation? :)
– Murillo Goulart
@Murillogoulart, the correct is indentation. Identar does not exist in Portuguese.
– Woss
@Andersoncarloswoss good comment, an additional: we have a community about Portuguese on the network and has this question including on the subject Ident, indent, or demonize?
– Guilherme Nascimento