Logo

dev-resources.site

for different kinds of informations.

10 Essential Best Practices for Writing High-Quality C++ Source Code

Published at
2/13/2023
Categories
cpp
cleancode
bestpractice
cppdepend
Author
codergears_team
Author
15 person written this
codergears_team
open
10 Essential Best Practices for Writing High-Quality C++ Source Code

Writing high-quality code is critical to the success of any software project, as it affects the reliability, performance, and maintainability of the code. In this blog post, we will discuss 10 essential best practices included in CppDepend for writing clean and efficient C++ source code. These best practices cover various aspects of coding, such as naming conventions, error handling, memory management, and more. Whether you are a beginner or an experienced programmer, following these best practices will help you write better C++ code and make your projects more successful.

1– Use descriptive and meaningful variable names: When naming variables, choose names that describe the purpose of the variable and are meaningful to the reader. This makes your code easier to read and understand.

#include <iostream>
​
int main()
{
    // GOOD EXAMPLE
    int userAge = 25;
    const int kDaysInWeek = 7;
    std::string firstName = "John";
​
    // BAD EXAMPLE
    int a = 25;
    int b = 7;
    std::string c = "John";
}
Enter fullscreen mode Exit fullscreen mode

2- Write readable code: Use proper indentation, whitespace, and comments to make your code easier to read. Additionally, break up long lines of code into smaller, more manageable blocks.

// GOOD EXAMPLE
for (int i = 0; i < 10; i++)
{
    cout << i << endl;
}
​
// BAD EXAMPLE
for(int i=0;i<10;i++)cout<<i<<endl;
Enter fullscreen mode Exit fullscreen mode

3- Use object-oriented programming: C++ is an object-oriented language, so make use of its features, such as classes and objects, to organize and structure your code.

#include <iostream>
#include <fstream>
​
int main()
{
    // GOOD EXAMPLE
    std::ifstream file("data.txt");
    if (!file.is_open())
    {
        std::cerr << "Error: Failed to open file." << std::endl;
        return 1;
    }
​
    // Read and process file data here
​
    file.close();
    return 0;
​
    // BAD EXAMPLE
    std::ifstream file("data.txt");
    // Read and process file data here
    file.close();
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

4- Avoid using global variables: Global variables can cause problems in larger projects, as they can easily be modified from different parts of the code. Instead, use local variables within functions and classes.

// GOOD EXAMPLE
void printSum(int x, int y)
{
    int sum = x + y;
    cout << "The sum is: " << sum << endl;
}
​
// BAD EXAMPLE
int sum;
​
void printSum(int x, int y)
{
    sum = x + y;
    cout << "The sum is: " << sum << endl;
}
Enter fullscreen mode Exit fullscreen mode

5- Make use of error handling: Make sure to handle errors and exceptions in your code, such as division by zero, invalid input, or out-of-bounds array access.

// GOOD EXAMPLE
int main()
{
    int dividend, divisor;
    cout << "Enter dividend: ";
    cin >> dividend;
    cout << "Enter divisor: ";
    cin >> divisor;
    try
    {
        if (divisor == 0)
        {
            throw runtime_error("Division by zero.");
        }
        cout << "Result: " << dividend / divisor << endl;
    }
    catch (runtime_error &err)
    {
        cout << err.what() << endl;
    }
    return 0;
}
​
// BAD EXAMPLE
int main()
{
    int dividend, divisor;
    cout << "Enter dividend: ";
    cin >> dividend;
    cout << "Enter divisor: ";
    cin >> divisor;
    if (divisor == 0)
    {
        cout << "Division by zero." << endl;
        return 1;
    }
    cout << "Result: " << dividend / divisor << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

6- Keep functions short and simple: Functions should be short and focused, with a single purpose. If a function becomes too complex, consider breaking it down into smaller, more manageable functions.

// GOOD EXAMPLE
int add(int x, int y)
{
    return x + y;
}
​
// BAD EXAMPLE
int addAndMultiply(int x, int y)
{
    int sum = x + y;
    int product = x * y;
    cout << "Sum: " << sum << endl;
    cout << "Product: " << product << endl;
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

7- Avoid hard-coding values: Instead of hard-coding values into your code, store them in constants or variables that can be easily changed. This makes your code more flexible and maintainable.

#include <iostream>
​
const int kDataSize = 100;
​
int main()
{
    // Good example
    int data[kDataSize];
    for (int i = 0; i < kDataSize; ++i)
        data[i] = i;
​
    // Bad example
    int data[100];
    for (int i = 0; i < 100; ++i)
        data[i] = i;
}
Enter fullscreen mode Exit fullscreen mode

8- Use standard libraries: C++ provides a rich set of standard libraries, including the Standard Template Library (STL), that can be used to perform common tasks. Making use of these libraries can simplify your code and improve performance.

// GOOD EXAMPLE
#include <iostream>
#include <string>
​
int main()
{
    std::string name;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
​
// BAD EXAMPLE
#include <iostream>
#include <string.h>
​
int main()
{
    char name[100];
    std::cout << "Enter your name: ";
    std::cin.getline(name, 100);
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

9- Keep code modular: Break your code into smaller, independent modules that can be easily tested and reused. This makes your code more maintainable and easier to modify.

// GOOD EXAMPLE
if (temperature > 30)
{
    cout << "It's hot outside." << endl;
}
else
{
    cout << "It's not hot outside." << endl;
}
​
// BAD EXAMPLE
if(temperature>30)cout<<"It's hot outside."<<endl;
else cout<<"It's not hot outside."<<endl;
Enter fullscreen mode Exit fullscreen mode

10- Document your code: Make sure to add comments to your code to describe its purpose, usage, and any assumptions that have been made. This makes it easier for others to understand your code and for you to remember how it works in the future.

#include <iostream>
​
// Good example
​
/**
 * Calculates the factorial of a given number.
 *
 * @param num The number to calculate the factorial of.
 * @return The factorial of the given number.
 */
unsigned long long factorial(unsigned int num)
{
    unsigned long long result = 1;
    for (int i = 2; i <= num; ++i)
        result *= i;
    return result;
}
​
// Bad example
​
unsigned long long f(unsigned int n)
{
    unsigned long long r = 1;
    for (int i = 2; i <= n; ++i)
        r *= i;
    return r;
}
Enter fullscreen mode Exit fullscreen mode

By following these best practices, you can write high-quality C++ source code that is easy to read, understand, and maintain.

Download CppDepend for free and see if your code is well-maintained!

bestpractice Article's
30 articles in total
Favicon
From Bi-weekly to Every 5 Minutes: Modern Continuous Deployment Strategies
Favicon
NotaciΓ³n Big O - Python
Favicon
Docker Advance Part 2: Docker Logging
Favicon
Client Extension no Liferay
Favicon
Dockerfile Best Practices: How to Create Efficient Containers
Favicon
Microservice Best Practices: Scale your java microservices using virtual threads & async programming
Favicon
Design Patterns for C
Favicon
Mastering React Hooks: Best Practices for Efficient and Maintainable Code
Favicon
Why You Should End Your Source Files With a New Line
Favicon
Puppet best practice
Favicon
@Nullable et @NonNull
Favicon
Component best practice question.
Favicon
How to Use CodeWhisperer to Identify Issues and Use Suggestions to Improve Code Security in your IDE
Favicon
Mastering React: Best Practices for Cleaner and More Efficient Code
Favicon
AWS Well-Architected Review in Action
Favicon
Improving Code Quality in Java: Best Practices and Examples
Favicon
Mastering JavaScript Event Handling for Enhanced Frontend Functionality
Favicon
TIL: Best Practices for Handling Secret Keys in Sinatra - The Do's and Don'ts
Favicon
Enhancing Website Accessibility: A Guide for Supporting Users with Disabilities
Favicon
Proposal for a framework.json file in Angular applications
Favicon
Part 3: Component Structure - Building Reusable and Maintainable Components in React!
Favicon
Using useReducer and Redux Toolkit Together: A Powerful Combination for State Management
Favicon
Separation of concerns in React and React Native.
Favicon
REST-API Design Best Practices
Favicon
Flags In Programming
Favicon
10 Essential Best Practices for Writing High-Quality C++ Source Code
Favicon
Avoiding code duplication in styled components
Favicon
Es mala prΓ‘ctica renderizar JSX en React Hook?
Favicon
ReactJS Best Practices
Favicon
Why you should adopt Makefile in all of your projects

Featured ones: