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
Filtered: 179 rules found
misra-c++2023
    Impact
      Clean code attribute
        1. "Predicates" shall not have "persistent side effects"

           Bug
        2. The C++ Standard Library functions "memcpy", "memmove" and "memcmp" from "<cstring>" shall not be used

           Code Smell
        3. A function call shall not violate the function's preconditions

           Bug
        4. Floating-point arithmetic should be used appropriately

           Bug
        5. The character handling functions from "<cctype>" and "<cwctype>" shall not be used

           Code Smell
        6. The "goto" statement should not be used

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

           Code Smell
        8. The literal value zero shall be the only value assigned to "errno"

           Code Smell
        9. A non-"transient lambda" shall not implicitly capture "this"

           Code Smell
        10. There shall be no occurrence of "undefined" or "critical unspecified behaviour"

           Bug
        11. User-defined identifiers shall have an appropriate form

           Code Smell
        12. "Legacy for statements" should be "simple"

           Code Smell
        13. A "for-range-initializer" shall contain at most one function call

           Bug
        14. "Global variables" shall not be used

           Code Smell
        15. The "volatile" qualifier shall be used appropriately

           Bug
        16. The built-in unary "+" operator should not be used

           Code Smell
        17. "Assignment" between numeric types shall be appropriate

           Code Smell
        18. "Integral promotion" and the "usual arithmetic conversions" shall not change the signedness or the "type category" of an operand

           Code Smell
        19. The operands of "bitwise operators" and "shift operators" shall be appropriate

           Bug
        20. There shall be no conversion to type "bool"

           Code Smell
        21. There shall be no conversion from type "bool"

           Code Smell
        22. The numerical value of a character shall not be used

           Code Smell
        23. "User-provided" copy and move member functions of a class should have appropriate signatures

           Code Smell
        24. "Special member functions" shall be provided appropriately

           Code Smell
        25. The argument to a "mixed-use macro parameter" shall not be subject to further expansion

           Code Smell
        26. An "object pointer type" shall not be cast to an integral type other than "std::uintptr_t" or "std::intptr_t"

           Code Smell
        27. The library function "system" from "<cstdlib>" shall not be used

           Vulnerability
        28. The pointers returned by the C++ Standard Library functions "localeconv", "getenv", "setlocale" or "strerror" must only be used as if they have pointer to const-qualified type

           Bug
        29. "Symmetrical operators" should only be implemented as non-member functions

           Code Smell
        30. "Exception-unfriendly" functions shall be "noexcept"

           Code Smell
        31. Member functions returning references to their object should be "ref-qualified" appropriately

           Code Smell
        32. An object shall not be accessed outside of its lifetime

           Bug
        33. A function declared with the "[[noreturn]]" attribute shall not return

           Bug
        34. If a project defines either a sized or unsized version of a global "operator delete", then both shall be defined

           Bug
        35. "std::vector" should not be specialized with "bool"

           Code Smell
        36. Variables of array type should not be declared

           Code Smell
        37. The "setlocale" and "std::locale::global" functions shall not be called

           Code Smell
        38. "User-provided" "copy assignment operators" and "move assignment operators" shall handle self-assignment

           Code Smell
        39. "User-declared" member functions shall use the "virtual", "override" and "final" specifiers appropriately

           Code Smell
        40. Derived classes shall not "conceal" functions that are inherited from their bases

           Code Smell
        41. A class shall only define an "initializer-list constructor" when it is the only constructor

           Code Smell
        42. "Unscoped enumerations" should not be declared

           Code Smell
        43. Functions with "limited visibility" should be "used" at least once

           Code Smell
        44. An "explicit type conversion" shall not be an "expression statement"

           Bug
        45. "Advanced memory management" shall not be used

           Code Smell
        46. Reads and writes on the same file stream shall be separated by a positioning operation

           Bug
        47. An argument passed via ellipsis shall have an appropriate type

           Bug
        48. Line-splicing shall not be used in "//" comments

           Bug
        49. A pointer to an incomplete "class" type shall not be deleted

           Bug
        50. All variables should be initialized

           Code Smell
        51. Octal escape sequences, hexadecimal escape sequences and universal character names shall be terminated

           Code Smell
        52. The result of "std::remove", "std::remove_if", "std::unique" and "empty" shall be "used"

           Bug
        53. The raw pointer constructors of "std::shared_ptr" and "std::unique_ptr" should not be used

           Code Smell
        54. An object shall not be used while in a "potentially moved-from state"

           Code Smell
        55. "Forwarding references" and "std::forward" shall be used together

           Code Smell
        56. The argument to "std::move" shall be a non-const "lvalue"

           Code Smell
        57. All direct, non-static data members of a class should be initialized before the class object is "accessible"

           Code Smell
        58. Dynamic memory shall be managed automatically

           Code Smell
        59. An enumeration shall be defined with an explicit underlying type

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

           Code Smell
        61. A comparison of a "potentially virtual" pointer to member function shall only be with "nullptr"

           Bug
        62. Variables should be captured explicitly in a non-"transient lambda"

           Code Smell
        63. Local variables shall not have static storage duration

           Code Smell
        64. Deprecated features should not be used

           Code Smell
        65. The C Library input/output functions shall not be used

           Code Smell
        66. The facilities provided by the standard "header file" "<csignal>" shall not be used

           Code Smell
        67. "Dynamic memory" should not be used

           Code Smell
        68. The macro "offsetof" shall not be used

           Code Smell
        69. The "string handling functions" from "<cstring>", "<cstdlib>", "<cwchar>" and "<cinttypes>" shall not be used

           Code Smell
        70. The pointer returned by the C++ Standard Library functions "asctime", "ctime", "gmtime", "localtime", "localeconv", "getenv", "setlocale" or "strerror" must not be used following a subsequent call to the same function

           Bug
        71. The library functions "atof", "atoi", "atol" and "atoll" from "<cstdlib>" shall not be used

           Bug
        72. The standard "header file" "<csetjmp>" shall not be used

           Code Smell
        73. The "#pragma" directive and the "_Pragma" operator should not be used

           Code Smell
        74. The "#" and "##" preprocessor operators should not be used

           Code Smell
        75. A macro parameter immediately following a "#" operator shall not be immediately followed by a "##" operator

           Code Smell
        76. The "#include" directive shall be followed by either a "<filename>" or ""filename"" sequence

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

           Bug
        78. Precautions shall be taken in order to prevent the contents of a "header file" being included more than once

           Code Smell
        79. All "#else", "#elif" and "#endif" preprocessor directives shall reside in the same file as the "#if", "#ifdef" or "#ifndef" directive to which they are related

           Code Smell
        80. The "defined" preprocessor operator shall be used appropriately

           Bug
        81. Program-terminating functions should not be used

           Code Smell
        82. A "noexcept" function should not attempt to propagate an exception to the calling function

           Bug
        83. An exception of "class" type shall be caught by "const" reference or reference

           Bug
        84. Handlers for a "function-try-block" of a constructor or destructor shall not refer to non-static members from their class or its bases

           Bug
        85. There should be at least one exception handler to catch all otherwise unhandled exceptions

           Bug
        86. An "empty throw" shall only occur within the "compound-statement" of a "catch handler"

           Code Smell
        87. An exception object shall not have pointer type

           Bug
        88. Function templates shall not be explicitly specialized

           Code Smell
        89. A name that is present in a dependent base shall not be resolved by unqualified lookup

           Code Smell
        90. Conversion operators and constructors that are callable with a single argument shall be "explicit"

           Code Smell
        91. All constructors of a class should explicitly initialize all of its virtual base classes and immediate base classes

           Code Smell
        92. An object's dynamic type shall not be used from within its constructor or destructor

           Code Smell
        93. Non-static data members should be either all "private" or all "public"

           Code Smell
        94. An accessible base class shall not be both virtual and non-virtual in the same hierarchy

           Bug
        95. Classes should not be inherited virtually

           Code Smell
        96. A named bit-field with "signed integer type" shall not have a length of one bit

           Bug
        97. A bit-field shall have an appropriate type

           Code Smell
        98. Bit-fields should not be declared

           Code Smell
        99. The "union" keyword shall not be used

           Code Smell
        100. Within an enumerator list, the value of an implicitly-specified "enumeration constant" shall be unique

           Code Smell
        101. The value of an object must not be read before it has been set

           Bug
        102. A conversion from function type to pointer-to-function type shall only occur in appropriate contexts

           Code Smell
        103. A function with non-"void" return type shall return a value on all paths

           Bug
        104. The parameters in all "declarations" or overrides of a function shall either be unnamed or have identical names

           Code Smell
        105. The features of "<cstdarg>" shall not be used

           Code Smell
        106. Parameters in an overriding virtual function shall not specify different default arguments

           Code Smell
        107. A "declaration" should not declare more than one variable or member variable

           Code Smell
        108. Functions shall not call themselves, either directly or indirectly

           Code Smell
        109. An assignment operator shall not assign the address of an object with automatic storage duration to an object with a greater lifetime

           Code Smell
        110. A function must not return a reference or a pointer to a local variable with automatic storage duration

           Bug
        111. The "asm" declaration shall not be used

           Code Smell
        112. There should be no unnamed namespaces in "header files"

           Code Smell
        113. The identifier "main" shall not be used for a function other than the global function "main"

           Code Smell
        114. The only "declarations" in the global namespace should be "main", namespace declarations and "extern "C"" declarations

           Code Smell
        115. The target type of a pointer or "lvalue" reference parameter should be const-qualified appropriately

           Code Smell
        116. The "goto" statement shall jump to a label declared later in the function body

           Code Smell
        117. A "goto" statement shall reference a label in a surrounding block

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

           Code Smell
        119. All "if ... else if" constructs shall be terminated with an "else" statement

           Code Smell
        120. The body of an "iteration-statement" or a "selection-statement" shall be a "compound-statement"

           Code Smell
        121. The result of an assignment operator should not be "used"

           Code Smell
        122. An unsigned arithmetic operation with constant operands should not wrap

           Bug
        123. The comma operator should not be used

           Code Smell
        124. The right-hand operand of a logical "&&" or "||" operator should not contain "persistent side effects"

           Bug
        125. The operand to "typeid" shall not be an expression of polymorphic class type

           Code Smell
        126. The "address-of" operator shall not be overloaded

           Code Smell
        127. The built-in unary "-" operator should not be applied to an expression of unsigned type

           Bug
        128. An array passed as a function argument shall not decay to a pointer

           Code Smell
        129. The logical AND and logical OR operators shall not be overloaded

           Code Smell
        130. A cast should not convert a pointer type to an integral type

           Code Smell
        131. An object with integral, enumerated, or pointer to "void" type shall not be cast to a pointer type

           Code Smell
        132. "reinterpret_cast" shall not be used

           Code Smell
        133. Casts shall not be performed between a pointer to function and any other type

           Bug
        134. A cast shall not remove any "const" or "volatile" qualification from the type accessed via a pointer or by reference

           Code Smell
        135. C-style casts and "functional notation" casts shall not be used

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

           Bug
        137. The "declaration" of an object should contain no more than two levels of pointer indirection

           Code Smell
        138. The built-in relational operators ">", ">=", "<" and "<=" shall not be applied to objects of pointer type, except where they point to elements of the same array

           Bug
        139. Subtraction between pointers shall only be applied to pointers that address elements of the same array

           Bug
        140. Pointer arithmetic shall not form an invalid pointer

           Bug
        141. Parentheses should be used to make the meaning of an expression appropriately explicit

           Code Smell
        142. Operations on a memory location shall be sequenced appropriately

           Bug
        143. "nullptr" shall be the only form of the "null-pointer-constant"

           Code Smell
        144. The numeric value of an "unscoped enumeration" with no fixed "underlying type" shall not be used

           Code Smell
        145. The names of the "standard signed integer types" and "standard unsigned integer types" should not be used

           Code Smell
        146. The same type aliases shall be used in all "declarations" of the same "entity"

           Code Smell
        147. Internal linkage should be specified appropriately

           Code Smell
        148. A function or object with external linkage should be "introduced" in a "header file"

           Code Smell
        149. The source code used to implement an "entity" shall appear only once

           Bug
        150. The "one-definition rule" shall not be violated

           Bug
        151. All "declarations" of a variable or function shall have the same type

           Bug
        152. When an array with external linkage is declared, its size should be explicitly specified

           Code Smell
        153. Block scope "declarations" shall not be "visually ambiguous"

           Code Smell
        154. A "header file" shall not contain definitions of functions or objects that are non-inline and have external linkage

           Code Smell
        155. A line whose first token is "#" shall be a valid preprocessing directive

           Bug
        156. All identifiers used in the controlling expression of "#if" or "#elif" preprocessing directives shall be defined prior to evaluation

           Bug
        157. Parentheses shall be used to ensure macro arguments are expanded appropriately

           Code Smell
        158. Tokens that look like a preprocessing directive shall not occur within a macro argument

           Bug
        159. Function-like macros shall not be defined

           Code Smell
        160. "#undef" should only be used for macros defined previously in the same file

           Code Smell
        161. "#include" directives should only be preceded by preprocessor directives or comments

           Code Smell
        162. String literals with different encoding prefixes shall not be concatenated

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

           Code Smell
        164. Unsigned "integer literals" shall be appropriately suffixed

           Code Smell
        165. Octal constants shall not be used

           Code Smell
        166. Within character literals and non raw-string literals, "\" shall only be used to form a defined escape sequence or universal character name

           Bug
        167. A variable declared in an "inner scope" shall not hide a variable declared in an "outer scope"

           Code Smell
        168. Sections of code should not be "commented out"

           Code Smell
        169. The character sequence "/*" shall not be used within a C-style comment

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

           Code Smell
        171. A program shall conform to ISO/IEC 14882:2017 (C++17)

           Code Smell
        172. An object or subobject must not be copied to an overlapping object

           Bug
        173. A named function parameter shall be "used" at least once

           Code Smell
        174. The value returned by a function shall be "used"

           Code Smell
        175. A value should not be "unnecessarily written" to a local object

           Code Smell
        176. Types with "limited visibility" should be "used" at least once

           Code Smell
        177. Variables with "limited visibility" should be "used" at least once

           Code Smell
        178. Controlling expressions should not be invariant

           Bug
        179. 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