Some computer languages require that statements appear one per line or start in certain columns. C/C++ does not have such restrictions. We can have multiple statements on a single line and can start a statement in any column. C/C++ allows us to include any amount of space, known as whitespace, in our code. Whitespace includes spaces, tabs, and blank lines. For example, all four of the following instructions are equivalent as far as the computer is concerned.
x = y + z - 47; /* Nicely formatted. */
x=y+z-47; // A bit too compact.
x = y + /* Rather spread out. */
z -
47;
/* The following is hard to read. */
x = y + z - 47;
In the following, there are two statements on a single line.
x = 27; y = 23456;
Note that whitespace cannot be placed within a single “programming element
” (formally known as a token), such as a number or a function name.
For example, if we were trying to write forty-seven, writing “4
7
” would be a bug. As another example, the function
“setup
()” cannot be written
“set up()”
(as discussed in the page about function basics, function names cannot contain
spaces).
Although C/C++ provides quite a bit of latitude in terms of the use of whitespace, the way in which whitespace is used can either enhance or detract from the readability of a sketch. For example, it is considered bad programming style to have multiple statements on a single line. So, a better way to write the two statements shown above is:
x = 27;
y = 23456;
Generally a single space should be placed between an operator and its operands. For example, the plus sign is an operator. The things being added are known as the operands. So, it would generally be considered better to write:
x = a + 10; // Nice.
Instead of:
x = a+10; // Not so nice.
Later you will see that indentation (i.e., the use of leading whitespace) plays an important role in creating readable sketches. For example, all the statements associated with the body of a function are usually indented to a particular column. This facilitates one's ability to group related statements together.