Uploaded image for project: 'SonarCFamily'
  1. SonarCFamily
  2. CPP-2996

Proposed Rule: Variable must be declared in a minimal scope

    XMLWordPrintable

    Details

    • Estimate:
      Days

      Description

      Declaring variables in the minimal scope might improve the readability of the code, cognitive load on the maintainer, and potentially performance.

      We implement a few special cases, namely: RSPEC-6170, RSPEC-6004, RSPEC-5955.
      There is also an old idea CPP-910.

      The scope is anything that can constrain the access to a name:

      • translation unit
      • function body
      • curly-braced block statement, including the loop and branch body
      • if, switch, range-for with an initializer
      • namespace
      • nested lambda or class/struct declaration

      Examples of non-covered cases:

      • move a global variable declaration inside a function body
      • move a variable declaration inside of an else-block of an if statement
      • move a local variable inside a body of the local lambda function
      • move a class field to a body of a member function

      The generic rule will have to watch out for

      • Non-trivial destructors (they are invoked at the end of the scope and hence changing the scope might change the behavior)
      • Statements invalidating initializer expressions for the variables we propose to move. I.e., one of the variables used in the initializer of the moved variable changes its value between the old and the new code points.
      • Aliasing. I.e., track if the variable is aliased, and the alias is used outside of the proposed small scope (to avoid use-after-free).

        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: