Readability best practices
What you'll learn: How to write code that is easy for humans to understand by using meaningful names and consistent spacing.
Code is for humans
Computers are surprisingly easy to please; as long as your syntax is perfect, the machine will run your instructions even if they look like a jumbled mess. However, code is read by humans far more often than it is written. Imagine opening a cookbook where the recipes don't have titles, the ingredients are labeled "Thing 1" and "Thing 2," and all the sentences are crammed together without punctuation. You might eventually figure out how to bake the cake, but it would be an exhausting headache.
In C, readability is your gift to your future self and your teammates. When you return to a project after three months, readable code tells you exactly what you were thinking.
Meaningful naming
The most powerful tool for readability is the variable name. A variable is a container for data, and its name should describe its contents.
Avoid cryptic, single-letter names like x, a, or q unless you are writing a very simple math formula. Instead, be descriptive. If you are storing the number of days until an event, call it daysUntilEvent. If you are storing a user's age, call it userAge.
Breathing room (Whitespace)
Whitespace refers to the tabs, spaces, and blank lines in your code. C doesn't care about whitespace, but humans do. Use indentation to show which lines of code belong together, and use blank lines to separate different "paragraphs" of logic.
Compare these two versions of the same logic:
// Hard to read (The "Jumbled Mess")
int main(){int d=10;int r=5;int t=d*r;return 0;}
// Easy to read (The "Readable Way")
int main() {
int daysWorking = 10;
int dailyRate = 5;
int totalEarnings = daysWorking * dailyRate;
return 0;
}
In the second example, the logic "breathes." You can instantly see that we are calculating earnings based on time and rate. By using clear names and vertical spacing, you’ve turned a math problem into a story that anyone can follow.
Key takeaway
Write code as if the person reading it is a tired friend who needs you to be as clear and organized as possible.