Tag: programming

  • 9 Tips for Writing Clean and Effective C/C++ Code

    Writing clean and effective code is essential for software developers. Not only does it make the code easier to maintain and update, but it also ensures that the code runs efficiently and without bugs. As a programming language, C/C++ is widely used in many applications, from system programming to game development. To help you write better C/C++ code, I’ve compiled a list of 10 tips from my laundry list of what makes good, clean, and effective C/C++ code. I hope these will guide you in making conscious decisions when coding, since many of these tips can be applied to other languages as well! So, whether you are an experienced C/C++ developer or just starting out, these tips will help you write cleaner, more efficient, and effective code.

    Tip #1: Variable Scope Awareness

    In C/C++, variables can have three different scopes: global scope, local scope, and member scope. Each of them have their place in software development and each have their own pros and cons.

    My rule of thumb is this. Make everything a local variable. If I need access to it in other object methods, I promote it to a member variable. If that still doesn’t work (which is extremely rare), then I make it a static global variable. With proper software design, I have found I never need to declare a true global variable, even if I protect it with appropriate locks.

    One last comment when dealing with global variables — you really should always make them const. The guidelines also state that you should always prefer scoped objects, rather than ones on the heap.

    Tip #2: Use Standard Types When Available

    Using standard type definitions in your C/C++ code has several benefits that can make your code more readable, portable, and maintainable. Here are some reasons why you should consider using standard type definitions in your code:

    1. Readability: Standard type definitions like size_t, int32_t, uint64_t, etc. are self-documenting and convey a clear meaning to the reader of your code. For example, using size_t instead of int to represent the size of a container makes it clear that the variable can only hold non-negative integers, which can help prevent bugs.
    2. Portability: Different platforms may have different data types with different sizes and behaviors. By using standard type definitions, you can ensure that your code is portable and will work consistently across different platforms.
    3. Type safety: Using standard type definitions can help prevent bugs caused by type mismatches, such as assigning a signed int to an unsigned int variable, or passing the wrong type of parameter as a function argument.
    4. Code maintenance: Standard type definitions can make your code easier to maintain by reducing the need for manual conversions and ensuring that the types of your variables are consistent throughout your codebase.

    Overall, using standard type definitions can help make your code more readable, portable, and maintainable, and following these recommendations can help you make conscious decisions about which type definitions to use in your code.

    Tip #3: Organize Related Data Into Objects

    When working with complex systems, it is often worthwhile to organize sets of data into objects for three primary reasons: encapsulation, abstraction, and modularity. Each of these are powerful principles that can help improve your code.

    Encapsulation

    Encapsulation is a fundamental principle of object-oriented programming and can help make your code more modular and maintainable.

    By organizing related data into an object, you can encapsulate the data and the operations that can be performed on it. This allows you to control access to the data and ensure that it is only modified in a safe and consistent way. In addition, you can make changes to the underlying data representation without changing the interface, which means that users of your object don’t have to change as well.

    Abstraction

    Objects allow you to abstract away the details of the data and provide a simplified interface for interacting with it. This can make your code easier to read and understand, as well as more resistant to changes in the underlying data representation.

    Modularity

    Organizing related data into an object can help you break down a large, complex problem into smaller, more manageable pieces. Each object can represent a distinct component of the system, with its own data and behavior, that can be developed and tested independently of the other components.

    Finally, once you have objects that you are manipulating, you can start returning those objects from your functions. Even cooler than that, you can return tuples containing your object and status information from your methods!

    Tip #4: Be Consistent in the Organization of Your Objects

    When you organize your data into objects and start defining member variables and methods, be consistent in the organization of your objects. For example, declare all public interface information up front, and keep all protected and private information at the end of the class.

    class BadExample
    {
    private:
      double m_data{73.0};
    
    public:
      BadExample();
      BadExample(const double &data) : m_data(data) {}
      ~BadExample();
    
      void SetFlag(const bool flag) { m_flag = flag; }
      void SetBytes(const std::size_t bytes) { m_nBytes = bytes; }
    
    private:
      bool m_flag{false};
      std::size_t m_nBytes{0};
    };
    
    class GoodExample
    {
    public:
      BadExample();
      BadExample(const double &data) : m_data(data) {}
      ~BadExample();
    
      void SetFlag(const bool flag) { m_flag = flag; }
      void SetBytes(const std::size_t bytes) { m_nBytes = bytes; }
    
    private:
      double m_data{73.0};
      bool m_flag{false};
      std::size_t m_nBytes{0};
    
      void SetData(const double data) { m_data = data; }
    };Code language: PHP (php)

    By declaring all private member variables and methods in a single private section, it makes the class definition much easier to read and follow. I know that when I read the GoodExample class definition that when I see the private keyword that everything coming after that keyword will be private and not accessible to me as a normal user.

    Tip #5: Place All Documentation in Header Files

    When you document your functions and variables, document them in the header file for one primary reason: keep the interface and implementation separate.

    Keeping the interface definition of your object separate from the implementation is a solid object-oriented design principle. The header file is where you define the interface for your users. That is where your users are going to look to understand what the purpose of a function is, how it should be used, what the arguments mean, and what the return value will contain. Many times the user of your object will not have access to the source code, so placing documentation there is pointless, from an interface perspective.

    Tip #6: Enforce a Coding Style

    Enforcing a code style can bring several benefits to your development process, including:

    1. Consistency: By enforcing a code style, you can ensure that your codebase looks consistent across different files and modules. This can make your code easier to read and understand, and can help reduce the amount of time developers spend trying to figure out how different parts of the codebase work.
    2. Maintainability: A consistent code style can also make your code easier to maintain, as it can help you identify patterns and common practices that are used throughout the codebase. This can make it easier to update and refactor the code, as you can more easily find and update all instances of a particular pattern.
    3. Collaboration: Enforcing a code style can also make it easier to collaborate with other developers, especially if they are working remotely or in different time zones. By using a consistent code style, developers can more easily understand each other’s code and can quickly identify where changes need to be made.
    4. Automation: Enforcing a code style with clang-format can also help automate the code review process, as it can automatically format code to the desired style. This can save time and effort in the code review process, and can ensure that all code is formatted consistently, even if developers have different preferences or habits.
    5. Industry standards: Many organizations and open-source projects have established code style guidelines that are enforced using tools like clang-format. By following these standards, you can ensure that your codebase adheres to best practices and can more easily integrate with other projects.

    Tip #7: Be const-Correct in All Your Definitions

    A major goal of mine when working in C and C++ is to make as many potential pitfalls and runtime bugs compiler errors rather than runtime errors. Striving to be const-correct in everything accomplishes a few things for the conscious coder:

    1. It conveys intent about what the method or variable should do or be. A const method cannot modify an object’s state, and a const variable cannot change its value post-declaration. This can make your code safer and reduce the risk of bugs and unexpected behavior.
    2. It makes your code more readable, as it can signal to other developers that the value of the object is not meant to be changed. This can make it easier for other developers to understand your code and can reduce confusion and errors.
    3. It allows the compiler to make certain optimizations that can improve the performance of your code. For example, the compiler can cache the value of a const object, which can save time in certain situations.
    4. It promotes a consistent coding style, making it easier for other developers to work with your code and reduce the risk of errors and confusion.
    5. It makes your code more compatible with other libraries and frameworks. Many third-party libraries require const-correctness in order to work correctly, so adhering to this standard can make it easier to integrate your code with other systems.

    Here are a couple of examples:

    class MyConstCorrectClass
    {
    public:
      MyConstCorrectClass() = default;
    
      void SetFlag(const bool flag) { m_flag = flag; } // Method not marked const because it modifies the state
                                                       // The argument is immutable though, and is thus marked const
      bool GetFlag() const { return m_flag' } // Marked as const because it does not modify state
    
    private:
      bool m_flag{false};
    };
    
    void function1(void)
    {
      MyConstCorrectClass A;
      A.SetFlag(true);
      std::cout << "A: " << A.GetFlag() << std::endl;
    
      const MyConstCorrectClass B;
      B.SetFlag(true);   // !! Compiler error because B is constant
      std::cout << "B: " << B.GetFlag() << std::endl;
    }Code language: PHP (php)

    Tip #8: Wrap Single-line Blocks With Braces

    Single-line blocks, such as those commonly found in if/else statements, should always be wrapped in braces. Beyond the arguments that it increases readability, maintainability, and consistency, for me this is a matter of safety. Consider this code:

    if (isSafe())
      setLED(LED::OFF);Code language: C++ (cpp)

    What happens when I need to take additional action when the function returns true? Sleeping developers would simply add the new action right after the setLED(LED::OFF) statement like this:

    if (isSafe())
      setLED(LED::OFF);
      controlLaser(LASER::ON, LASER::HIGH_POWER);
    Code language: C++ (cpp)

    Now consider the implications of such an action. The controlLaser(LASER::ON, LASER::HIGH_POWER); statement gets run every single time, not just if the function isSafe() returns true. This has serious consequences, which is exactly why you should always wrap your single-line blocks with braces!

    if (isSafe())
    {
      setLED(LED::OFF);
      controlLaser(LASER::ON, LASER::HIGH_POWER);
    }
    Code language: C++ (cpp)

    Tip #9: Keep Your Code Linear — Return from One Spot

    This is also known as the “single exit point” principle, but the core of it is that you want your code to be linear. Linear code is easier to read, to maintain, and debug. When you return from a function in multiple places, this can lead to hard to follow logic that obscures what the developer is really trying to accomplish. Consider this example:

    std::string Transaction::GetUUID(void) const
    {
      std::string uuid = xg::Guid();  // empty ctor for xg::Guid gives a nil UUID
      if (m_library->isActionInProgress())
      {
        return m_library->getActionIdInProgress();
      }
      return uuid;
    }
    Code language: C++ (cpp)

    This seems fairly simple to follow and understand, but it doesn’t follow the single exit point principle — the flow of the method is non-linear. If the logic in this function ever gets more complex, this can quickly get harder to debug. This simple change here ensures that the flow is linear and that future modifications follow suit.

    std::string Transaction::GetUUID(void) const
    {
      std::string uuid = xg::Guid();  // empty ctor for xg::Guid gives a nil UUID
      if (m_library->isActionInProgress())
      {
        uuid = m_library->getActionIdInProgress();
      }
      return uuid;
    }
    Code language: C++ (cpp)

    You may argue that the first function is slightly more efficient because you save the extra copy to the temporary variable uuid. But most any modern compiler worth using will optimize that copy out, and you’re left with the same performance in both.

    A quick bit of wisdom — simple code, even if it has more lines, more assignments, etc. is more often than not going to result in better performance than complex code. Why? The optimizer can more readily recognize simple constructs and optimize them than it can with complex algorithms that perform the same function!


    Conclusion

    In this post, we covered a variety of topics related to C++ programming best practices. We discussed the benefits of using standard type definitions, the importance of organizing related data into objects, the placement of function documentation comments, the use of clang-format to enforce code style, the significance of being const-correct in all your definitions, and the reasons why it is important to wrap single-line blocks with braces and to return from only a single spot in your function.

    By adhering to these best practices, C++ programmers can create code that is more readable, maintainable, and easy to debug. These principles help ensure that code is consistent and that common sources of errors, such as memory leaks or incorrect program behavior, are avoided.

    Overall, by following these best practices, C++ programmers can create high-quality, efficient, and robust code that can be easily understood and modified, even as the codebase grows in size and complexity.

  • Mastering Variable Scopes in C/C++: Best Practices for Clean and Effective Code

    As software developers, we rely on variables to store and manipulate data in our programs. However, it is crucial to understand the scope of a variable and how it affects its accessibility and lifetime. In C and C++, the scope of a variable determines where in the program it can be used and for how long it will exist. In this blog post, we will be exploring the different types of scopes in C/C++ and the best practices for handling them to write clean, maintainable, and effective code.

    We will look at global, local, and member scopes and how they affect the lifetime of variables. We will also discuss how to properly handle pointers, which have their own unique set of considerations when it comes to scope. By understanding the different types of scopes and how to handle them, you will be equipped to make conscious decisions about how you use variables in your code, leading to more reliable, efficient, and maintainable programs.

    Variable Scope Awareness

    Awareness of variable lifetimes and scopes, particularly when it comes to pointers, is critical to writing clean and effective C/C++ code. The lifetime of a variable is the period of time during which it is allocated memory and exists in the program. In C/C++, variables can have three different scopes: global scope, local scope, and member scope.

    Global Scope Variables

    Global scope variables are declared outside of all functions and are accessible throughout the entire program. They have a longer lifetime and persist throughout the execution of the program, but using too many global scope variables can lead to cluttered code and potential naming conflicts. However, in my mind, the more serious implications of improper use of a global variable is race conditions.

    A race condition occurs when two or more threads access a shared resource, such as a global variable, simultaneously and the final result depends on the timing of the access. In a safety critical environment, where errors in the system can have severe consequences, race conditions can cause significant harm.

    // Example of a global variable, including a potential race condition
    int32_t g_temperature_C = 0;
    
    void thread1(void)
    {
      // Read the temperature from the sensor
      g_temperature_C = ReadTemperatureFromSensor();
    }
    
    void thread2(void)
    {
      if ((g_temperature_C > 0) && (g_temperature_C < 70)) // !! Simple race condition
      {
        // Do some safety critical work
      }
      else
      {
        // Manage temperature out of bounds (i.e., cool down or heat up)
      }
    }
    Code language: C++ (cpp)

    In the example above, thread2 is doing some safety critical work, but only when g_temperature_C is within a certain range, which is updated in thread1. If the temperature is out of bounds, then the system needs to take a different action. The issue here is that the wrong action can lead to serious consequences, either for the safety of the system, or in the case where humans are involved, the safety of the user.

    In this case, a global variable is a poor choice of scope for g_temperature_C.

    If you find you do have to use global variables, you can still limit their scope to the specific compilation unit where they are defined (i.e., the file where the variable is declared). You can do this by adding the static keyword to the variable declaration. The advantage to this is that it limits the scope of the variable to just the specific module, rather than the entire program.

    // Limit scope of global variable to the specific compilation unit (i.e., this file)
    static int32_t g_temperature_C = 0;
    Code language: C++ (cpp)

    Local Scope Variables

    Local scope variables, on the other hand, are declared within a function or block and are only accessible within that specific scope. They have a shorter lifetime, are allocated on the stack, and are automatically deallocated from memory once the function or block has finished execution. Using local scope variables is recommended over global variables as they limit the potential for naming conflicts, allow for cleaner code, and also eliminate race conditions.

    // Example of a local variable, resolving the race condition above
    void thread2(void)
    {
      int32_t l_temperature_C = ReadTemperatureFromSensor();
      if ((l_temperature_C > 0) && (l_temperature_C < 70)) // !! NO race condition
      {
        // Do some safety critical work
      }
      else
      {
        // Manage temperature out of bounds (i.e., cool down or heat up)
      }
    }
    Code language: C++ (cpp)

    As you can see, the race condition from using a global variable is avoided here because the variable is local and cannot be changed outside of this function.

    Member Scope Variables

    Member scope variables, also known as class member variables, are declared within a class and are accessible by all member functions of that class. Their scope is tied to the lifetime of the object they are a member of.

    #include <iostream>
    
    class TemperatureSensor
    {
    public:
      TemperatureSensor() = default;
    
      void GetTemperature()
      {
        m_temp_C = ReadTemperatureFromSensor();
        return m_temp_C;
      }
    
    private:
      int32_t m_temp_C{0};
    };
    
    int main()
    {
      TemperatureSensor sensor;
      std::cout << "Temperature: " << sensor.GetTemperature() << std::endl;
      std::cout << "Temperature: " << sensor.GetTemperature() << std::endl;
    
      return 0;
    }Code language: PHP (php)

    You can think of the scope of member variables to be similar to that of static global variables. Instead of being limited to the compilation unit where they are declared, they are limited to the scope of the class that they are part of. Race conditions on member variables are a real possibility. Precautions must be taken to ensure you avoid them, such as proper locking or an improved architecture to avoid the race altogether.

    Properly Scoping Pointers

    Pointers are a powerful tool in C and C++, allowing you to efficiently work with data objects in your programs. However, naive usage of pointers can lead to significant problems, including hard to find bugs and difficult to maintain code.

    In C and C++, pointers have their own lifetime, separate from the objects they point to. When a pointer goes out of scope, the object it referenced remains in memory but is no longer accessible. When dynamically allocating memory, this leads to memory leaks where the memory is not properly deallocated, leading to a buildup of memory usage over time.

    Smart Pointers

    To prevent memory leaks and ensure that your programs are efficient and reliable, it is important to handle pointers with care. Modern C++ provides smart pointers types, which automatically manage the lifetime of objects and deallocate them when they are no longer needed. Using smart pointer types of std::shared_ptr and std::unique_ptr, you can be assured that when you create (and allocate) a pointer to an object, that object is constructed (and initialized if following RAII principles) and the pointer is valid. Then, when that pointer goes out of scope, the object is destructed and the memory is deallocated.

    #include <memory>
    #include <iostream>
    
    void PrintTemperature()
    {
      // Create a unique pointer to a TemperatureSensor object
      std::unique_ptr<TemperatureSensor> pTS = std::make_unique<TemperatureSensor>();
      
      // Use the unique pointer within the scope of the current function
      std::cout << "Temperature: " << pTS->GetTemperature() << std::endl;
      
      // The unique pointer goes out of scope at the end of the main function
      // and its dynamically allocated memory is automatically deallocated
    
    }Code language: PHP (php)

    When working with raw pointers, it’s critical to be aware of the lifetime of the objects being pointed to. For example, if the lifetime of the object ends before the pointer is deallocated, the pointer becomes a “dangling pointer”. This can cause undefined behavior, such as crashing the program or returning incorrect results. Smart pointers are typically a better choice and avoid this risk by managing the lifetime of the object themselves.


    In conclusion, understanding and properly handling the scope of variables in C/C++ is a crucial aspect of writing clean, maintainable, and effective code. By becoming familiar with global, local, and member scopes, and considering the lifetime and accessibility of variables, you can make informed decisions about how to use variables in your programs.

    Additionally, pointers require their own set of considerations when it comes to scope, and it is essential to handle them with care to prevent memory leaks and other issues.

    By following best practices and being aware of the potential pitfalls, you can ensure that your programs are reliable, efficient, and easy to maintain.