Skip to main content

Section 2.7 Formatting Source Code

In C++ source code, some spaces are required. For example, you need at least one space between words, so this program is not legal. Try running it to see what error message you get.
Listing 2.7.1.
But most other spaces are optional. For example, this program is legal:
Listing 2.7.2.
The newlines are optional, too. So we could just write this:
Listing 2.7.3.
It still works, but the program is getting harder and harder to read. Newlines and spaces are important for visually organizing your program, making it easier to understand the program and find errors when they occur.

Insight 2.7.1.

We write code to communicate not just with the compiler, but also to communicate with other humans. The compiler doesn’t care about spaces or newlines, but humans do. Code that is formatted in a consistent way is easier to read and understand.
There are conventions for not just where to use spaces, but where to break lines of code up, how to indent code, etc... Sometimes, there is more than one convention - some programmers prefer using tabs to indent lines of code, while others prefer spaces (often if you press the tab key, your editor will automatically turn it into a series of spaces).
When working alone, a programmer can pick any style they like. However, when programmers are collaborating, it is important to share a consistent style. Organizations that do a lot of software development usually have strict guidelines on how to format source code. For example, Google publishes its C++ coding standards. You probably won’t understand these guidelines now, because they refer to language features you haven’t yet seen. But you might want to refer to them periodically as you read this book.
The good news is that most code editors will help automatically format source code and can even re-format code that is not well-formatted. You may have to do a little work to tell the editor what style you want to use, but then it can help, make sure your code is well formatted.

Checkpoint 2.7.1.

Which best expresses what is true about whitespace (spaces and newlines) in C++ programs?
  • C++ cares strongly about exactly where you place whitespace.
  • C++ is actually pretty flexible about whitespace.
  • C++ is flexible about whitespace, but using it consistently and following conventions is important for human programmers.
  • There is not one "true" style, but it is important that programmers working together use consistent styling.
  • C++ is flexible about whitespace, so each programmer should develop their own personal style.
  • We write code as much for other people as we do for computers. It is important that others can look at your code and quickly make sense of it.
You have attempted of activities on this page.