Loading lessons...
Whitespace and Basic Formatting
Whitespace and Basic Formatting
Whitespace means the "empty" characters: spaces, tabs, and newlines. C++ shrugs at most of them.
The compiler ignores whitespace
Outside of strings, extra spaces and newlines don't change behaviour:
int x = 5;
int x = 5;
Both compile and do the same thing. But wow - the second one is unpleasant!
One place whitespace counts
Inside a string literal, spaces are part of the text:
cout << "hello world"; // keeps the space
cout << "helloworld"; // different text!
Also, you generally can't split a keyword or identifier by spaces: in t is not int.
What the whitespace is for: readability
Indentation - moving nested code in with tabs or spaces - tells you at a glance what belongs inside a block:
int main() {
if (age > 5) {
cout << "Big kid!";
}
}
The inner line is indented one more level because it belongs to the if. Even though the compiler doesn't need this, your future self does.
Style notes
- Pick one style (spaces vs tabs, brace on the same line) and stick to it.
- Consistent formatting makes bugs easy to spot, since odd lines "pop out".
- Many teams use a tool (clang-format) to auto-format everyone's code.
TL;DR
- Whitespace = spaces, tabs, and newlines; the compiler ignores it (except inside strings).
- Indentation has no effect, but it's great for readability.
- Indent nested code to show it "belongs to" the block above.
- Stay consistent with your formatting everywhere.