Indentation

What is indentation?

Indentation is when some lines of a code or text start closer to the right than others.

Example of an indented code:

1
2
3
4
5
6
int main() { int var = 5; return 0; }

The same code, but not indented:

1
2
3
4
5
6
int main() { int var = 5; return 0; }

To make lines start closer to the right, we use tabulations (The keyboard key TAB). The rule is that elements contained inside an other element (Inside braces {}) start closer to the right by one tabulation than the element that contains them.

An other example of an indented code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> // 0 tabulation: Not contained by anything. int main() { // 1 tabulation: contained by 'int main()' which starts with 0 tabulation. int var = 5; // 1 tabulation: contained by 'int main()' which starts with 0 tabulation. if(var == 5) // We will learn about 'if' and the operator '==' very soon. { // 2 tabulations: contained by 'if' which starts with 1 tabulation. std::cout << "Equals 5." << std::endl; } // 1 tabulation: contained by 'int main()' which starts with 0 tabulation. return 0; }

We have not seen the structure if yet, it has been used here only to demonstrate indentation because it contains elements inside braces {}.

The same example as above, without indentation:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> int main() { int var = 5; if(var == 5) { std::cout << "Equals 5." << std::endl; } return 0; }

Indented code is easier to understand, so it is important to do it.

Sustainable code

When we write code, we want it to be sustainable so we can improve it constantly and be able to reuse it again and again, without having to remake it because it became a mess.

There are the 5 keys to achieving that:

If those 5 points are followed, the odds that your code becomes a mess are extremely diminished.