Naming & Formatting
Conventions in C++
Write code that humans can read: learn the rules for consistent naming, indentation, and formatting that make C++ programs clean, professional, and maintainable.
C++
Best Practices
Why Do Conventions Matter?
Code is read far more often than it is written. Consistent naming and formatting conventions ensure that every member of a team (and your future self) can understand code quickly without guessing what a variable means or where a block begins.
Readability
Clean names and indentation let you scan code like reading a book.
Collaboration
Teams move faster when everyone follows the same style rules.
Debugging
Consistent formatting makes bugs stand out visually.
Key Terminology
Identifier
Any name you create: variables, functions, classes, constants, namespaces.
Naming Convention
A rule for how identifiers are capitalized and separated (e.g., camelCase).
Formatting Convention
Rules for whitespace, indentation, brace placement, and line length.
The Convention Landscape
The Naming Rules
1
Variables and functions: use camelCase or snake_case: playerScore, calculate_total.
2
Classes and structs: use PascalCase: GameEngine, StudentRecord.
3
Constants and macros: use UPPER_SNAKE_CASE: MAX_SIZE, PI_VALUE.
4
Namespaces: use lowercase with underscores: game_utils, math_lib.
The Formatting Rules
1
Indentation: use a consistent number of spaces (typically 4 spaces) per level. Never mix tabs and spaces.
2
Brace placement: place the opening brace on the same line (K&R style) or the next line (Allman style): pick one.
3
Line length: keep lines under 80-120 characters. Break long expressions cleanly.
4
Blank lines: separate logical sections with one blank line. Use two blank lines between function definitions.
camelCase vs snake_case
| camelCase | snake_case | |
|---|---|---|
| Variable | playerHealth | player_health |
| Function | calculateArea | calculate_area |
| Used By | JavaScript, Java, C# | C++ STL, Google C++, Python |
| Key Trait | Compact, fewer characters | Higher readability at a glance |
How to Apply Conventions
1
Choose a style guide: Google C++ Style, LLVM, or your team's own guide.
2
Configure your editor: set up clang-format or an equivalent tool to auto-format on save.
3
Name with intent: every identifier should describe what it holds or what it does, not how it works.
4
Review before commit: scan for inconsistent names, stray tabs, long lines, and missing blank lines.
5
Refactor old code: when you touch legacy code, update its naming to match the project convention.
Example 1: Variable Naming
✕ Poor Names
int x = 42;
double d = 3.14;
string s = "Alice";
bool flag = true;
int temp = x * 2;
✓ Descriptive Names
int studentAge = 42;
double circleRadius = 3.14;
string firstName = "Alice";
bool isEnrolled = true;
int doubledAge = studentAge * 2;
Example 2: Functions & Classes
✕ Inconsistent
class player_Data {
int HP;
void TAKE_damage(int d);
};
int Calc(int a, int b);
✓ Consistent
class PlayerData {
int hitPoints;
void takeDamage(int amount);
};
int calculateSum(int a, int b);
Example 3: Complete Formatting
✕ Messy
int main(){
int x=5;
if(x > 3){
cout << "big";
}
else{
cout << "small";}
return 0;}
✓ Clean
int main() {
int itemCount = 5;
if (itemCount > 3) {
cout << "big";
} else {
cout << "small";
}
return 0;
}
Constants & Macros
// Constants: UPPER_SNAKE_CASE
const int MAX_STUDENTS = 30;
constexpr double PI_VALUE = 3.14159265;
// Macros: also UPPER_SNAKE_CASE
#define BUFFER_SIZE 1024
// Instead of #define, modern C++ prefers:
constexpr int BUFFER_SIZE_CONST = 1024; // Better!
Brace Styles Compared
K&R / 1TBS
if (x > 0) {
doWork();
}
doWork();
}
Allman
if (x > 0)
{
doWork();
}
{
doWork();
}
Common Mistakes
✕ Single-Letter Names
Using x, n, t for non-trivial variables. Loop counters (i, j) are the only exception.
✕ Mixing Styles
Writing playerHP next to enemy_health in the same file. Pick one convention.
✕ Inconsistent Indentation
Using 2 spaces in one function and 4 in another, or mixing tabs with spaces.
✕ Misleading Names
Naming a list data or a boolean status when it should be studentList or isActive.
Convention Summary
| Identifier Type | Convention | Example |
|---|---|---|
| Local variable | camelCase / snake_case | itemCount |
| Function | camelCase / snake_case | getTotal() |
| Class / Struct | PascalCase | LinkedList |
| Constant | UPPER_SNAKE_CASE | MAX_RETRIES |
| Namespace | lowercase / snake_case | file_io |
| Member variable | Prefix/suffix (e.g., m_, _) | m_count |
Question 1 of 5
Which naming convention is most appropriate for a C++ class name?
Classes and structs in C++ conventionally use PascalCase (each word capitalized, no underscores). UPPER_SNAKE_CASE is reserved for constants and macros.
Question 2 of 5
What is wrong with the following code?
const int maxStudents = 30;
int StudentCount = 0;
bool is_full = false;
The constant uses camelCase, the variable uses PascalCase, and the boolean uses snake_case. All three should follow the same convention within a project. The constant should also be MAX_STUDENTS (UPPER_SNAKE_CASE).
Question 3 of 5
Which of the following is the best name for a boolean variable that tracks whether a file has been saved?
Boolean variables should read like a yes/no question. isSaved clearly communicates its purpose. save sounds like a verb (action), flag is meaningless, and fileSaveStatus is vague since a "status" could be many types.
Question 4 of 5
In the K&R (1TBS) brace style, where does the opening brace go?
In the K&R / 1TBS style, the opening brace is placed on the same line as the statement: if (x > 0) {. The Allman style places it on the next line.
Question 5 of 5
Which line violates standard C++ naming conventions?
1. class ShapeRenderer { ... };
2. constexpr int MAX_VERTICES = 256;
3. void Calculate_Area(double r);
4. int vertexCount = 0;
Calculate_Area mixes PascalCase with an underscore separator, which does not match any standard convention. It should be calculateArea (camelCase) or calculate_area (snake_case). All other lines follow their respective conventions correctly.