Indentation
Indentation is a programming practice that enhances the readability of source code. It is also known as indentation or typesetting.
What is Indentation?
Indentation involves adjusting the position of instructions within lines of source code by adding whitespace before them.
if (age<18) {
printf('Access denied');
access = False;
}
This technique is known as the off-side rule.
Why is Indentation Important?
Indentation makes it easier to quickly understand if an instruction belongs to a block of a program's logical structure (conditional, control, or iterative) and its nesting.
As a result, source code becomes more readable and understandable for developers.
Note: Generally, whitespace is ignored by compilers and interpreters and does not cause errors. For example, in languages like C or PHP, the position of an instruction within the source code lines doesn’t matter.
How to Indent Code
All text editors allow for the insertion of whitespace or tabs before instructions.
In some editors, indentation is manual, while in others, it is automatic.
What is Significant Indentation?
In some programming languages, whitespace affects the execution of the program.
In these cases, it is referred to as significant indentation.
Example
In the Python language, indentation replaces braces in conditional structures.
if age<18:
print('Access denied')
access = False
else:
print('Access granted')
access = True
Non-Significant Indentation
Non-significant indentation occurs when whitespace does not affect the program's execution.
Example
In the C language, indentation only serves to enhance the readability of the source code and does not affect execution.
if (age<18) {
printf('Access denied');
access = False;
}
The same applies to languages like PHP, Basic, and others.