SonarSource Rules
  • Products

    In-IDE

    Code Quality and Security in your IDE with SonarQube Ide

    IDE extension that lets you fix coding issues before they exist!

    Discover SonarQube for IDE

    SaaS

    Code Quality and Security in the cloud with SonarQube Cloud

    Setup is effortless and analysis is automatic for most languages

    Discover SonarQube Cloud

    Self-Hosted

    Code Quality and Security Self-Hosted with SonarQube Server

    Fast, accurate analysis; enterprise scalability

    Discover SonarQube Server
  • SecretsSecrets
  • ABAPABAP
  • AnsibleAnsible
  • ApexApex
  • AzureResourceManagerAzureResourceManager
  • CC
  • C#C#
  • C++C++
  • CloudFormationCloudFormation
  • COBOLCOBOL
  • CSSCSS
  • DartDart
  • DockerDocker
  • FlexFlex
  • GitHub ActionsGitHub Actions
  • GoGo
  • HTMLHTML
  • JavaJava
  • JavaScriptJavaScript
  • JSONJSON
  • JCLJCL
  • KotlinKotlin
  • KubernetesKubernetes
  • Objective CObjective C
  • PHPPHP
  • PL/IPL/I
  • PL/SQLPL/SQL
  • PythonPython
  • RPGRPG
  • RubyRuby
  • RustRust
  • ScalaScala
  • ShellShell
  • SwiftSwift
  • TerraformTerraform
  • TextText
  • TypeScriptTypeScript
  • T-SQLT-SQL
  • VB.NETVB.NET
  • VB6VB6
  • XMLXML
  • YAMLYAML
C++

C++ static code analysis

Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your C++ code

  • All rules 798
  • Vulnerability14
  • Bug173
  • Security Hotspot19
  • Code Smell592

  • Quick Fix 99
 
Tags
    Impact
      Clean code attribute
        1. Pointer and reference parameters should be "const" if the corresponding object is not modified

           Code Smell
        2. Non-standard characters should not occur in header file names in "#include" directives

           Bug
        3. Objects or functions with external linkage shall be declared in a header file

           Code Smell
        4. Functions should not be declared at block scope

           Code Smell
        5. Literal suffix "L" for long integers shall be upper case

           Code Smell
        6. Digraphs should not be used

           Code Smell
        7. std::string_view::data() should not be passed to API expecting C-style strings

           Code Smell
        8. "std::size" should be used to determine the size of arrays

           Code Smell
        9. Calls to c_str() should not implicitly recreate strings or string_views

           Code Smell
        10. The first element of an array should not be accessed implicitly

           Code Smell
        11. Escape sequences should use the delimited form (\u{}, \o{}, \x{})

           Code Smell
        12. "contains" should be used to test whether a substring is part of a string

           Code Smell
        13. "if consteval" should be used instead of "if (std::is_constant_evaluated())"

           Code Smell
        14. The condition of "assert" should not be trivially true

           Code Smell
        15. A single L in a literal suffix should only be used for long values

           Code Smell
        16. "static_assert" should be preferred to assert when the argument is a compile-time constant

           Code Smell
        17. Aggregates should be initialized with braces in non-generic code

           Code Smell
        18. "constexpr" literal operators should be "consteval".

           Code Smell
        19. Assigning to an optional should directly target the optional

           Bug
        20. Use type-erased "coroutine_handle" when applicable

           Code Smell
        21. "auto" should be used to store a result of functions that conventionally return an iterator or a range

           Code Smell
        22. Comparision operators ("<=>", "==") should be defaulted unless non-default behavior is required

           Code Smell
        23. "starts_with" and "ends_with" should be used for prefix and postfix checks

           Code Smell
        24. "using enum" should be used in scopes with high concentration of "enum" constants

           Code Smell
        25. "contains" should be used to check if a key exists in a container

           Code Smell
        26. Elements in a container should be erased with "std::erase" or "std::erase_if"

           Code Smell
        27. "emplace" should be prefered over "insert" with "std::set" and "std::unordered_set"

           Code Smell
        28. Unnecessary expensive copy should be avoided when using auto as a placeholder type

           Code Smell
        29. The right template argument should be specified for std::forward

           Code Smell
        30. "try_emplace" should be used with "std::map" and "std::unordered_map"

           Code Smell
        31. "std::optional" member function "value_or" should be used

           Code Smell
        32. The "_t" and "_v" version of type traits should be used instead of "::type" and "::value"

           Code Smell
        33. "[*this]" should be used to capture the current object by copy

           Code Smell
        34. "static_assert" with no message should be used over "static_assert" with empty or redundant message

           Code Smell
        35. Objects should not be created solely to be passed as arguments to functions that perform delegated object creation

           Code Smell
        36. "as_const" should be used to make a value constant

           Code Smell
        37. "if" and "switch" initializer should be used to reduce scope of variables

           Code Smell
        38. Emplacement should be preferred when insertion creates a temporary with sequence containers

           Code Smell
        39. Values returned from string find-related methods should not be treated as boolean

           Bug
        40. Loop variables should be declared in the minimal possible scope

           Code Smell
        41. "shared_ptr" should not be taken by rvalue reference

           Code Smell
        42. Inheriting constructors should be used

           Code Smell
        43. Return type of functions shouldn't be const qualified value

           Code Smell
        44. "make_unique" and "make_shared" should be used to construct "unique_ptr" and "shared_ptr"

           Code Smell
        45. "auto" should be used to avoid repetition of types

           Code Smell
        46. Integer literals should not be cast to bool

           Code Smell
        47. Member functions that don't mutate their objects should be declared "const"

           Code Smell
        48. Concise syntax should be used for concatenatable namespaces

           Code Smell
        49. Capture by reference in lambdas used locally

           Code Smell
        50. "using" should be preferred for type aliasing

           Code Smell
        51. "std::move" should only be used where moving can happen

           Code Smell
        52. "constexpr" functions should not be declared "inline"

           Code Smell
        53. Pointer and reference local variables should be "const" if the corresponding object is not modified

           Code Smell
        54. Lambdas that capture "this" should capture everything explicitly

           Code Smell
        55. "nullptr" should be used to denote the null pointer

           Code Smell
        56. String literals should not be immediately followed by macros

           Code Smell
        57. Alternative operators should not be used

           Code Smell
        58. "reinterpret_cast" should not be used

           Code Smell
        59. Raw string literals should be used

           Code Smell
        60. "static" should not be used in unnamed namespaces

           Code Smell
        61. Default capture should not be used

           Code Smell
        62. "final" classes should not have "virtual" functions

           Code Smell
        63. Standard groupings should be used with digit separators

           Code Smell
        64. Digit separators should be used

           Code Smell
        65. Access specifiers should not be redundant

           Code Smell
        66. Special member function should not be defined unless a non standard behavior is required

           Code Smell
        67. "override" or "final" should be used instead of "virtual"

           Code Smell
        68. Members should be initialized in the order they are declared

           Code Smell
        69. "sizeof" should not be called on pointers

           Bug
        70. Control characters should not be used in literals

           Code Smell
        71. Parameters should be passed in the correct order

           Code Smell
        72. "static" members should be accessed statically

           Code Smell
        73. "final" should not be used redundantly

           Code Smell
        74. Redundant casts should not be used

           Code Smell
        75. "explicit" should be used on single-parameter constructors and conversion operators

           Code Smell
        76. Multiple variables should not be declared on the same line

           Code Smell
        77. Unused local variables should be removed

           Code Smell
        78. Octal values should not be used

           Code Smell
        79. Functions without parameters should not use "(void)"

           Code Smell
        80. A "while" loop should be used instead of a "for" loop

           Code Smell
        81. Sections of code should not be commented out

           Code Smell
        82. Pass by reference to const should be used for large input parameters

           Code Smell
        83. Overriding member functions should do more than simply call the same member in the base class

           Code Smell
        84. "empty()" should be used to test for emptiness

           Code Smell
        85. Redundant pairs of parentheses should be removed

           Code Smell
        86. Handlers in a single try-catch or function-try-block for a derived class and some or all of its bases should be ordered most-derived-first

           Bug
        87. Exception classes should be caught by reference

           Bug
        88. Virtual functions should be declared with the "virtual" keyword

           Code Smell
        89. An "integer-literal" of type "long long" shall not use a single "L" or "l" in any suffix

           Code Smell
        90. The raw pointer constructors of "std::shared_ptr" and "std::unique_ptr" should not be used

           Code Smell
        91. The "assert" macro shall not be used with a "constant-expression"

           Code Smell
        92. The "'" or """ or "\" characters and the "/*" or "//" character sequences shall not occur in a "header file" name

           Bug
        93. A "declaration" should not declare more than one variable or member variable

           Code Smell
        94. The structure of a "switch" statement shall be appropriate

           Code Smell
        95. A virtual base class shall only be cast to a derived class by means of "dynamic_cast"

           Bug
        96. The lowercase form of "L" shall not be used as the first character in a literal suffix

           Code Smell
        97. Octal constants shall not be used

           Code Smell
        98. "Trigraph-like sequences" should not be used

           Code Smell
        99. A function shall not contain "unreachable" statements

           Bug

        The structure of a "switch" statement shall be appropriate

        intentionality - clear
        maintainability
        reliability
        Code Smell
        Quick FixIDE quick fixes available with SonarQube for IDE
        • misra-c++2023
        • misra-required

        Why is this an issue?

        More Info

        This rule is part of MISRA C++:2023.

        Usage of this content is governed by Sonar’s terms and conditions. Redistribution is prohibited.

        Rule 9.4.2 - The structure of a switch statement shall be appropriate

        [stmt.switch]
        [dcl.attr.fallthrough]

        Category: Required

        Analysis: Decidable,Single Translation Unit

        Amplification

        The substatement of a switch statement is called the switch body. It shall be a compound statement.

        A labeled statement, along with the complete chain of its substatements that are also labeled statements, is called a label group. A label group that is directly enclosed by a switch body is called a switch label group.

        The statements directly enclosed by a switch body are partitioned into switch branches, with each switch label group starting a new branch.

        A switch statement is structured appropriately when it conforms to the following restrictions:

        • The condition shall only be preceded by an optional simple-declaration;
        • case or default labeled statements shall only appear as part of a switch label group;
        • Switch label groups shall only contain case or default labeled statements;
        • The first statement in a switch body shall be a switch label group;
        • Every switch branch shall be unconditionally terminated by either:
          • A break statement; or
          • A continue statement; or
          • A return statement; or
          • A goto statement; or
          • A throw expression; or
          • A call to a [[noreturn]] function; or
          • A [[fallthrough]] attribute applied to a null statement.
        • Every switch statement shall have at least two switch branches;
        • Every switch statement shall have a default label, appearing as either the first label of the first switch label group or as the last label of the last switch label group.

        Rationale

        The syntax for the switch statement can be used to create complex, unstructured code. This rule places restrictions on the use of the switch statement in order to impose a simple and consistent structure:

        • A simple-declaration is permitted before the condition as it allows the declaration of a variable with restricted scope within a switch statement. An expression-statement is not permitted as the init-statement, as it introduces complexity without any extra benefit.
        • The C++ Standard permits a case label or default label to be placed before any statement contained within the body of a switch statement, potentially leading to unstructured code. To prevent this, a case label or default label is only permitted to appear at the outermost level of the compound statement forming the body of a switch statement.
        • Including labels other than case or default in a switch label group potentially allows unstructured control flow to be introduced.
        • A statement placed before a switch label group would either be an uninitialized variable or unreachable code.
        • If a developer fails to terminate a switch branch, then control flow "falls" into the following switch branch or, if there is no such branch, off the end and into the statement following the switch statement. The requirement for unconditional termination ensures that unintentional fall-throughs can be detected, with the [[fallthrough]] attribute being used to explicitly indicate when fall-through is intentional. Note: fall-through that occurs between two consecutive case or default labels having no intervening statements is not ambiguous, and is permitted by this rule.
        • A switch statement with a single switch branch is not permitted as it may be indicative of a programming error.
        • The requirement for a default label is defensive programming, complementing the requirement for if ... else if constructs to be terminated with an else (see M23_112: MISRA C++ 2023 Rule 9.4.1). The addition of a default, even when empty, indicates that consideration has been given regarding the behaviour when all other cases are not selected. Placing the default as the first or last label makes it easier to locate during code review.

        Note: even when the condition of a switch has enum type, listing all enumerators values in case labels does not make the use of default redundant as the value could still lie outside of the set of enumerators.

        Exception

        If the condition of a switch statement is an unscoped enumeration type that does not have a fixed underlying type, and all the enumerators are listed in case labels, then a default label is not required. Note: compliance with M23_061: MISRA C++ 2023 Rule 10.2.3 ensures that an object of such a type cannot be assigned values outside of its set of enumerators.

        Example

        The following switch statement has four switch branches:

        switch ( int8_t x = f(); x ) // Compliant - declaration of x is simple
        {
          case 1:
          {
            break;                   // Compliant - branch unconditionally terminated
          }
        
          case 2:
          case 3:
            throw;                   // Compliant - branch unconditionally terminated
        
          case 4:
            a++;
            [[fallthrough]];         // Compliant - branch has explicit fall-through
          default:                   // Compliant - default is last label
            b++;
            return;                  // Compliant - branches unconditionally terminated
        }
        

        The following switch statement has four switch branches:

        switch ( x = f(); x )        // Non-compliant - x = f() is not a simple-declaration
        {
          int32_t i;                 // Non-compliant - not a switch label group
        
          case 5:
            if ( ... )
            {
              break;
            }
            else
            {
              break;
            }
                                     // Non-compliant - termination is not unconditional
        
          case 6:
            a = b;                   // Non-compliant - non-empty, implicit fall-through
          case 7:
            {
              case 8:                // Non-compliant - case not in a switch label group
                DoIt();
            }
            break;
        }                            // Non-compliant - default is required
        
        switch ( x )                 // Non-compliant - only one switch branch
        {
          default:
            ;                        // Non-compliant - default must also be terminated
        }
        
        enum Colours { RED, GREEN, BLUE } colour;
        
        switch ( colour )
        {
          case RED:
            break;
          case GREEN:
            break;
        }                            // Non-compliant - default is required
        
        switch ( colour )
        {
          case RED:
          case GREEN:
            break;
          case BLUE:
            break;
        }                            // Compliant by exception - all enumerators listed
        
        switch ( colour )            // Non-compliant - only one switch branch
        {
          case RED:
          default:                   // Non-compliant - default must be first or last label
          case BLUE:
            break;
        }
        

        Copyright The MISRA Consortium Limited © 2023

          Available In:
        • SonarQube IdeCatch issues on the fly,
          in your IDE
        • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
        • SonarQube ServerAnalyze code in your
          on-premise CI

        © 2025 SonarSource Sàrl. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use