Variable Naming Rules in C++


TL ; DR:

  • In C++, we use the camelCase convention to name our variables. It implies separating different words with capital letters, like this:

    string companyName = "Apple";
    
    int foundingYear = 1976;
    
    bool isUnicorn = true;
    
    int numberOfEmployees = 137000;
    





Full lesson:

Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.

Bad variable names:

int 18spam;
string x.15;
bool #name;

If you try to create a variable with any of these names, C++ will throw an error.


Naming conventions: camelCase and snake_case

Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:

string first name = "Kate";

This code will also throw an error.

When you name your variables, you want to use one of these two conventions:

snake_case = separate different words with an underscore (_), like this:

string first_name = "Jane";
string last_name = "Doe";

camelCase = separate different words with capital letters, like this:

string firstName = "Jane";
string lastName = "Doe";

It's important to be consistent with the casing technique you use. Do not combine both of them in the same code, like this:

string first_name = "Jane";
string lastName = "Doe";

Case sensitive:

Variable names are case sensitive:

string name = "Kate";
string Name = "Andy";
string NAME = "George";

cout << name << " " << Name << " " << NAME; // Output: Kate Andy George

Although C++ allows us to do this, it's always confusing and a bad coding practice to differentiate variable names just by case!


Mnemonic Variable Names:

Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".

Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.

Here is a great example:

int a = 25;
int b = 13;
int c = a * b;
cout << c;

compared to:

int hours = 25;
int rate = 13;
int pay = hours * rate;
cout << pay;

C++ understands and is happy with both of these pieces of code. But it's clearly which version makes your reader happier.

Assignment
Follow the Coding Tutorial and let's name some variables well!


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the rules and best practices for naming variables in C++. Proper variable naming is crucial for writing clear, maintainable, and error-free code. Understanding these rules will help you avoid common pitfalls and improve your coding efficiency.

Understanding the Basics

Variable names in C++ must consist only of letters, numbers, and underscores, and they must start with a letter or an underscore. This ensures that variable names are easily readable and do not conflict with C++ keywords or other symbols.

For example:

int age = 25;
string firstName = "John";
bool isStudent = true;

These are valid variable names. However, names like 18spam, x.15, and #name are invalid and will cause errors.

Main Concepts

There are two main naming conventions in C++: camelCase and snake_case. CamelCase separates words with capital letters, while snake_case uses underscores.

For example:

string firstName = "Jane"; // camelCase
string last_name = "Doe";   // snake_case

Consistency is key. Do not mix these conventions within the same codebase.

Examples and Use Cases

Let's look at some examples to understand the application of these naming conventions:

string companyName = "Apple";
int foundingYear = 1976;
bool isUnicorn = true;
int numberOfEmployees = 137000;

These examples use camelCase, which is common in C++ for variable names.

Common Pitfalls and Best Practices

Avoid using variable names that differ only by case, as this can lead to confusion and errors:

string name = "Kate";
string Name = "Andy";
string NAME = "George";

While C++ allows this, it is considered bad practice. Instead, use descriptive and unique names for variables.

Advanced Techniques

For more advanced variable naming, consider using prefixes or suffixes to indicate the type or purpose of the variable. For example:

int numEmployees = 137000;
bool isActive = true;
string strCompanyName = "Apple";

This can make your code more readable and easier to understand.

Code Implementation

Here is a well-commented code snippet demonstrating proper variable naming:

// Define company details
string companyName = "Apple"; // Name of the company
int foundingYear = 1976;      // Year the company was founded
bool isUnicorn = true;        // Whether the company is a unicorn
int numberOfEmployees = 137000; // Number of employees

// Output company details
cout << "Company: " << companyName << endl;
cout << "Founded: " << foundingYear << endl;
cout << "Is Unicorn: " << (isUnicorn ? "Yes" : "No") << endl;
cout << "Employees: " << numberOfEmployees << endl;

Debugging and Testing

When debugging, ensure that variable names are clear and descriptive to make it easier to identify issues. Write tests to verify that variables hold the expected values:

#include <cassert>

void testCompanyDetails() {
    string companyName = "Apple";
    int foundingYear = 1976;
    bool isUnicorn = true;
    int numberOfEmployees = 137000;

    assert(companyName == "Apple");
    assert(foundingYear == 1976);
    assert(isUnicorn == true);
    assert(numberOfEmployees == 137000);
}

int main() {
    testCompanyDetails();
    cout << "All tests passed!" << endl;
    return 0;
}

Thinking and Problem-Solving Tips

When naming variables, think about the purpose and context of the variable. Break down complex problems into smaller parts and name variables accordingly. Practice by writing code and reviewing it to ensure clarity and consistency.

Conclusion

Mastering variable naming rules in C++ is essential for writing clear and maintainable code. By following best practices and avoiding common pitfalls, you can improve your coding efficiency and reduce errors. Practice regularly to become proficient in naming variables effectively.

Additional Resources