Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-6179

"std::midpoint" and "std::lerp" should be used for midpoint computation and linear interpolation

    XMLWordPrintable

    Details

    • Message:
      Hide
      * Use "std::midpoint" to compute the midpoint between X and Y.
      * Use "std::lerp" to compute linear interpolation between X and Y.
      Show
      * Use "std::midpoint" to compute the midpoint between X and Y. * Use "std::lerp" to compute linear interpolation between X and Y.
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      C++20 introduced the standard algorithms to compute the midpoint between two values and linear interpolation for a given coefficient.

      std::midpoint(a, b) computes the midpoint, or average, or arithmetic mean of two values a and b: (a+b)/2. The result is half-way from a to b, and if a and b are pointers it points to the middle of a contiguous memory segment between the two. A naive midpoint computation might suffer from a possible overflow or be inefficient. That's why in most cases std::midpoint is preferable.

      std::lerp(a, b, t) returns linear interpolation between values a and b with a coefficient t: a+t*(a-b), where t is between 0 and 1.

      This rule reports computations that should be replaced with std::midpoint or std::lerp.

      Noncompliant Code Example

      auto avg1 = (a + b)/2; // Noncompliant, might overflow
      auto avg2 = a + (b - a)/2; // Noncompliant
      auto third = a + (b - a)*0.3f; // Noncompliant
      

      Compliant Solution

      auto avg1 = std::midpoint(a, b);
      auto avg2 = std::midpoint(a, b);
      auto third = std::lerp(a, b, 0.3f);
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              arseniy.zaostrovnykh Arseniy Zaostrovnykh
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: