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 the second one is unpleasant!
One place whitespace counts
Inside a string literal, spaces are part of the text:
printf("hello world"); // keeps the space
printf("helloworld"); // different text!
What whitespace is for: readability
Indentation tells you at a glance what belongs inside a block:
int main() {
if (age > 5) {
printf("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".
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.