- Choose an indentation size: Common choices are 2 or 4 spaces. Some styles use tabs, but spaces are generally more consistent across editors.
- Indent each new code block: Inside any set of
{ }, increase the indentation level by one. When you exit that block, decrease the indentation level.
Example (indenting 4 spaces):
int main() {
int x = 10;
if (x > 5) {
// Inside an if block, so we indent further
x += 5;
}
return 0;
}- Around operators:
x = 10;(rather thanx=10;) - After commas in function arguments:
function(a, b, c); - Between control structures and parentheses (many styles prefer
if (condition)instead ofif(condition)).
Whitespace usage helps code readability, so it's good to show how it impacts scanning and readability.
There are a few common brace styles. Pick one style and stay consistent. Two popular ones are:
-
K&R Style (also known as One True Brace Style):
int main() { // code }
The opening brace is on the same line as the statement.
-
Allman Style (brace on its own line):
if (x > 5) { x += 10; } else { x--; }
- Encourage a limit on line length (say 80 or 100 characters) to avoid horizontal scrolling.
- When a line of code is too long, break it in a logical place (e.g., after a comma, after an operator, etc.).
-
If a function call's parameter list is long, place each argument on its own line, indented once:
myFunction(longArgumentName, anotherArgument, lastArgument);
-
For complex
ifstatements or loops:if (someCondition && anotherCondition && yetAnotherCondition) { // ... }
Use blank lines to separate logical sections of code: group related lines together, then use a blank line before the next section.
Example:
// 1. Variable initialization
int a = 0;
int b = 5;
// 2. Processing
a = b + 10;
// 3. Final Output
std::cout << a << std::endl;While naming conventions aren't strictly "formatting," they often go hand in hand with clean code. Consistency in naming variables and functions also makes the code more readable. For instance:
- snake_case or camelCase for variables/functions
- PascalCase for classes
Example:
// camelCase
int playerHealth = 100;
void updateHealth(int changeAmount);
// snake_case
int player_health = 100;
void update_health(int change_amount);