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 674
  • Vulnerability13
  • Bug139
  • Security Hotspot19
  • Code Smell503

  • Quick Fix 91
 
Tags
    Impact
      Clean code attribute
        1. "goto" should jump to labels declared later in the same function

           Code Smell
        2. The name "main" should not be used for any function other than the global "main" function

           Code Smell
        3. The global namespace should only contain "main", namespace declarations, and "extern" C declarations

           Code Smell
        4. Pointer and reference parameters should be "const" if the corresponding object is not modified

           Code Smell
        5. A variable which is not modified shall be const qualified

           Code Smell
        6. "<time.h>" should not be used

           Code Smell
        7. "abort", "exit", "getenv" and "system" from <stdlib.h> should not be used

           Bug
        8. "atof", "atoi" and "atol" from <stdlib.h> should not be used

           Bug
        9. "<stdio.h>" should not be used in production code

           Code Smell
        10. "<signal.h>" should not be used

           Bug
        11. "offsetof" macro should not be used

           Code Smell
        12. "errno" should not be used

           Code Smell
        13. Dynamic heap memory allocation should not be used

           Bug
        14. "setjmp" and "longjmp" should not be used

           Code Smell
        15. Reserved identifiers should not be defined or declared

           Code Smell
        16. Lines starting with "#" should contain valid preprocessing directives

           Bug
        17. Only standard forms of the "defined" directive should be used

           Code Smell
        18. Preprocessor operators "#" and "##" should not be used

           Code Smell
        19. There shall be at most one occurrence of the # or ## operators in a single macro definition

           Code Smell
        20. Macros used in preprocessor directives should be defined before use

           Bug
        21. In the definition of a function-like macro, each instance of a parameter shall be enclosed in parentheses, unless it is used as the operand of # or ##

           Code Smell
        22. Function-like macros should not be invoked without all of their arguments

           Bug
        23. Function-like macros should not be used

           Code Smell
        24. "#undef" should be used with caution

           Code Smell
        25. Macros should not be #define'd or #undef'd within a block

           Code Smell
        26. "#include" directives should be followed by either <filename> or "filename" sequences

           Bug
        27. Non-standard characters should not occur in header file names in "#include" directives

           Bug
        28. #include directives in a file should only be preceded by other preprocessor directives or comments

           Code Smell
        29. Unions should not be used

           Code Smell
        30. The address of an automatic object should not be assigned to another object that may persist after the first object has ceased to exist

           Bug
        31. Array type function arguments should not decay to pointers

           Code Smell
        32. Object declarations should contain no more than 2 levels of pointer indirection

           Code Smell
        33. Function names should be used either as a call with a parameter list or with the "&" operator

           Code Smell
        34. Function exit paths should have appropriate return values

           Bug
        35. Parameters in a function prototype should be named

           Code Smell
        36. Recursion should not be used

           Code Smell
        37. Loops should not have more than one "break" or "goto" statement

           Code Smell
        38. Functions should not be defined with a variable number of arguments

           Code Smell
        39. Evaluation of the operand to the sizeof operator shall not contain side effects

           Bug
        40. Switch statement conditions should not have essentially boolean type

           Code Smell
        41. The comma operator, "&&", and "||" should not be overloaded

           Code Smell
        42. Switch labels should not be nested inside non-switch blocks

           Code Smell
        43. The right-hand operands of && and || should not contain side effects

           Code Smell
        44. "continue" should not be used

           Code Smell
        45. "goto" statement should not be used

           Code Smell
        46. Non-empty statements should change control flow or have at least one side-effect

           Bug
        47. Unused type declarations should be removed

           Code Smell
        48. A loop-control-variable other than the loop-counter which is modified in statement shall have type bool

           Code Smell
        49. The loop-counter should be modified by one of: --, ++, -=n, or +=n; where n remains constant for the duration of the loop

           Code Smell
        50. The three expressions of a "for" statement should only be concerned with loop control

           Code Smell
        51. Increment (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression

           Code Smell
        52. Comma operator should not be used

           Code Smell
        53. The unary "&" operator should not be overloaded

           Code Smell
        54. Unary minus should not be applied to an unsigned expression

           Bug
        55. Bitwise operators should not be applied to signed operands

           Bug
        56. "enum" values should not be used as operands to built-in operators other than [ ], =, ==, !=, unary &, and the relational operators <, <=, >, >=

           Code Smell
        57. "bool" expressions should not be used as operands to built-in operators other than =, &&, ||, !, ==, !=, unary &, and the conditional operator

           Code Smell
        58. C-style and functional notation casts should not be used

           Code Smell
        59. Operands of "&&" and "||" should be primary (C) or postfix (C++) expressions

           Code Smell
        60. Boolean operations should not have numeric operands, and vice versa

           Bug
        61. Limited dependence should be placed on operator precedence

           Code Smell
        62. Objects with integer type should not be converted to objects with pointer type

           Bug
        63. A cast shall not remove any const or volatile qualification from the type of a pointer or reference

           Code Smell
        64. Pointer conversions should be restricted to a safe subset

           Bug
        65. Function pointers should not be converted to any other type

           Bug
        66. Constants of unsigned type should have a "U" suffix

           Code Smell
        67. Results of ~ and << operations on operands of underlying types unsigned char and unsigned short should immediately be cast to the operand's underlying type

           Bug
        68. Signed and unsigned types should not be mixed in expressions

           Code Smell
        69. "enum" members with implicit values should not collide with other enumerators

           Code Smell
        70. Variables should be initialized before use

           Bug
        71. Braces should be used to indicate and match the structure in the non-zero initialization of arrays and structures

           Code Smell
        72. Array declarations should include an explicit size specification

           Code Smell
        73. If a function has internal linkage then all re-declarations shall include the static storage class specifer

           Code Smell
        74. Objects or functions with external linkage shall be declared in a header file

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

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

           Code Smell
        77. String literals with different prefixes should not be concatenated

           Bug
        78. Bit fields should be declared with appropriate types

           Code Smell
        79. typedefs that indicate size and signedness should be used in place of the basic types

           Code Smell
        80. The first operand of a conditional operator should have type bool

           Code Smell
        81. The condition of an if-statement and the condition of an iteration-statement shall have type bool

           Code Smell
        82. Appropriate char types should be used for character and integer values

           Code Smell
        83. Identifiers should not be longer than 31 characters

           Code Smell
        84. Digraphs should not be used

           Code Smell
        85. Trigraphs should not be used

           Code Smell
        86. Only escape sequences defined in the ISO C standard should be used

           Bug
        87. All uses of the #pragma directive should be documented

           Code Smell
        88. Source code should only use /* ... */ style comments

           Code Smell
        89. Assembly language should be encapsulated and isolated

           Code Smell
        90. Named methods should be used to avoid confusion between testing an optional or an expected and testing the wrapped value

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

           Code Smell
        92. String literals should not be assigned to mutable char pointers

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

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

           Code Smell
        95. Globals should not depend on possibly not yet initialized variables

           Code Smell
        96. String methods should be used to query content instead of C apis

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

           Code Smell
        98. "std::views::as_const" should be used to prevent modifying range elements

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

           Code Smell
        100. "std::stringstream" or "std::spanstream" should be used instead of "std::strstream"

           Code Smell
        101. The underlying value of an enum should be accessed through "to_underlying"

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

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

           Code Smell
        104. The optional init-statement in a control statements should only be used to declare variables

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

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

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

           Code Smell
        108. Macro arguments should not contain preprocessing directives

           Bug
        109. Names of well-known C standard library macros and functions should not be used as identifiers

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

           Code Smell
        111. All the elements of an aggregate should be provided with an initial value

           Code Smell
        112. Variables should not be accessed outside of their scope

           Bug
        113. Coroutines should have well-defined exception behavior

           Bug
        114. "constexpr" literal operators should be "consteval".

           Code Smell
        115. "std::format" should be used instead of standard output manipulators

           Code Smell
        116. C++ formatting functions should be used instead of C printf-like functions

           Code Smell
        117. The result of "make_format_args" should be passed directly as an argument

           Bug
        118. Use "std::format" rather than "std::vformat" when the format string is known at compile time

           Code Smell
        119. "std::format" numeric types should be 0-padded using the numerical padding and not the character padding

           Bug
        120. Arguments corresponding to width and precision formatting options should be integers

           Bug
        121. Calls to "std::format" with a locale should use the "L" flag

           Code Smell
        122. "std::format" should not have unused arguments

           Code Smell
        123. "std::format" should not be missing indexes

           Bug
        124. Concatenated "std::format" outputs should be replaced by a single invocation

           Code Smell
        125. Width, alignment, and padding format options should be used consistently

           Code Smell
        126. Explicit argument indexing in "std::format" should be used only for non-trivial ordering

           Code Smell
        127. Generic iterator-based algorithms should be constrained

           Code Smell
        128. "std::declval" should not be used within requires-expression

           Code Smell
        129. Template should not be constrained with ad-hoc requires-expression

           Code Smell
        130. Type-constraints should not be used for forwarding reference parameters

           Bug
        131. Perfect forwarding constructors should be constrained

           Bug
        132. Requires-expression should not contain unevaluated concept checks or type predicates

           Bug
        133. Assigning to an optional should directly target the optional

           Bug
        134. Hard-coded secrets are security-sensitive

           Security Hotspot
        135. Coroutines should not take const references as parameters

           Code Smell
        136. Use type-erased "coroutine_handle" when applicable

           Code Smell
        137. Coroutine should have co_return on each execution path or provide return_void

           Bug
        138. Thread local variables should not be used in coroutines

           Code Smell
        139. Use conditional suspension to resume current coroutine

           Code Smell
        140. Use symmetric transfer to switch execution between coroutines

           Code Smell
        141. The return value of "std::move" should be used in a function

           Code Smell
        142. rvalue reference members should not be copied accidentally

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

           Code Smell
        144. Well-defined type-punning method should be used instead of a union-based one

           Bug
        145. "std::string_view" and "std::span" parameters should be directly constructed from sequences

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

           Code Smell
        147. "std::chrono" components should be used to operate on time

           Code Smell
        148. "std::has_single_bit" should be used to test if an integer is a power of two

           Code Smell
        149. Empty class members should be marked as "[[no_unique_address]]"

           Code Smell
        150. "std::to_address" should be used to convert iterators to raw pointers

           Code Smell
        151. Result of the standard remove algorithms should not be ignored

           Bug
        152. "[[nodiscard]]" attributes on types should include explanations

           Code Smell
        153. Concept names should comply with a naming convention

           Code Smell
        154. "std::cmp_*" functions should be used to compare unsigned values with negative values

           Bug
        155. "volatile" should not be used to qualify objects for which the meaning is not defined

           Bug
        156. STL constrained algorithms with range parameter should be used when iterating over the entire range

           Code Smell
        157. "std::enable_if" should not be used

           Code Smell
        158. Cognitive Complexity of coroutines should not be too high

           Code Smell
        159. Coroutine names should comply with a naming convention

           Code Smell
        160. Cyclomatic Complexity of coroutines should not be too high

           Code Smell
        161. "volatile" types should not be used in compound operations

           Bug
        162. "std::source_location" should be used instead of "__FILE__", "__LINE__", and "__func__" macros

           Code Smell
        163. Function template parameters should be named if reused

           Code Smell
        164. "std::span" should be used for a uniform sequence of elements contiguous in memory

           Code Smell
        165. Operator spaceship "<=>" should be used to define comparable types

           Code Smell
        166. Redundant comparison operators should not be defined

           Code Smell
        167. "std::format" should be used instead of string concatenation and "std::to_string"

           Code Smell
        168. Coroutines should not have too many lines of code

           Code Smell
        169. "std::cmp_*" functions should be used to compare signed and unsigned values

           Code Smell
        170. "std::bit_cast" should be used to reinterpret binary representation instead of "std::memcpy"

           Code Smell
        171. "[[likely]]" and "[[unlikely]]" should be used instead of compiler built-ins

           Code Smell
        172. "std::midpoint" and "std::lerp" should be used for midpoint computation and linear interpolation

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

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

           Code Smell
        175. Designated initializers should be used in their C++ compliant form

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

           Code Smell
        177. "std::is_constant_evaluated" and "if consteval" should only be used when necessary

           Bug
        178. "std::jthread" should be used instead of "std::thread"

           Code Smell
        179. "nodiscard" attributes on functions should include explanations

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

           Code Smell
        181. Mathematical constants should not be hardcoded

           Code Smell
        182. Use discriminated unions or "std::variant"

           Code Smell
        183. "sprintf" should not be used

           Security Hotspot
        184. Transparent function objects should be used with associative "std::string" containers

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

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

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

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

           Code Smell
        189. Exception specifications should be treated as part of the type

           Code Smell
        190. "auto" should be used for non-type template parameter

           Code Smell
        191. Use "std::variant" instead of unions with non-trivial types.

           Code Smell
        192. Free functions should be preferred to member functions when accessing a container in a generic context

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

           Code Smell
        194. "std::byte" should be used when you need byte-oriented memory access

           Code Smell
        195. Heterogeneous sorted containers should only be used with types that support heterogeneous comparison

           Bug
        196. The "_t" and "_v" version of type traits should be used instead of "::type" and "::value"

           Code Smell
        197. Inline variables should be used to declare global variables in header files

           Code Smell
        198. "if constexpr" should be preferred to overloading for metaprogramming

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

           Code Smell
        200. "std::uncaught_exception" should not be used

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

           Code Smell
        202. Redundant class template arguments should not be used

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

           Code Smell
        204. "std::filesystem::path" should be used to represent a file path

           Code Smell
        205. "std::string_view" should be used to pass a read-only string to a function

           Code Smell
        206. Fold expressions should be used instead of recursive template instantiations

           Code Smell
        207. [[nodiscard]] should be used when the return value of a function should not be ignored

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

           Code Smell
        209. Structured binding should be used

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

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

           Code Smell
        212. "std::visit" should be used to switch on the type of the current value in a "std::variant"

           Code Smell
        213. "std::scoped_lock" should be created with constructor arguments

           Bug
        214. "std::scoped_lock" should be used instead of "std::lock_guard"

           Code Smell
        215. "bind" should not be used

           Code Smell
        216. Changing working directories without verifying the success is security-sensitive

           Security Hotspot
        217. "dynamic_cast" should be used for downcasting

           Code Smell
        218. Multicharacter literals should not be used

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

           Bug
        220. Struct should explicitly specify the access level when specifying base classes

           Code Smell
        221. Classes should explicitly specify the access level when specifying base classes

           Code Smell
        222. "std::initializer_list" constructor should not overlap with other constructors

           Code Smell
        223. Threads should not be detached

           Code Smell
        224. Loop variables should be declared in the minimal possible scope

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

           Code Smell
        226. Inheriting constructors should be used

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

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

           Code Smell
        229. "std::endl" should not be used

           Code Smell
        230. C-style array should not be used

           Code Smell
        231. Objects should not be sliced

           Bug
        232. Setting capabilities is security-sensitive

           Security Hotspot
        233. Accessing files should not introduce TOCTOU vulnerabilities

           Vulnerability
        234. Account validity should be verified when authenticating users with PAM

           Vulnerability
        235. "auto" should be used to avoid repetition of types

           Code Smell
        236. Macros should not be used as replacements for "typedef" and "using"

           Code Smell
        237. Using "tmpnam", "tmpnam_s" or "tmpnam_r" is security-sensitive

           Security Hotspot
        238. Integer literals should not be cast to bool

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

           Code Smell
        240. Using "strncpy" or "wcsncpy" is security-sensitive

           Security Hotspot
        241. Using "strncat" or "wcsncat" is security-sensitive

           Security Hotspot
        242. Using "strcat" or "wcscat" is security-sensitive

           Security Hotspot
        243. Using "strlen" or "wcslen" is security-sensitive

           Security Hotspot
        244. Concise syntax should be used for concatenatable namespaces

           Code Smell
        245. Changing directories improperly when using "chroot" is security-sensitive

           Security Hotspot
        246. Using "strcpy" or "wcscpy" is security-sensitive

           Security Hotspot
        247. "memset" should not be used to delete sensitive data

           Vulnerability
        248. POSIX functions should not be called with arguments that trigger buffer overflows

           Vulnerability
        249. Relational and subtraction operators should not be used with pointers to different arrays

           Bug
        250. Track comments matching a regular expression

           Code Smell
        251. Arguments evaluation order should not be relied on

           Bug
        252. STL algorithms and range-based for loops should be preferred to traditional for loops

           Code Smell
        253. Immediately dangling references and pointers should not be created

           Bug
        254. Cipher algorithms should be robust

           Vulnerability
        255. Encryption algorithms should be used with secure mode and padding scheme

           Vulnerability
        256. Functions that are not used in a project should be removed

           Code Smell
        257. Server hostnames should be verified during SSL/TLS connections

           Vulnerability
        258. Multiple mutexes should not be acquired with individual locks

           Code Smell
        259. Local variables should be initialized immediately

           Code Smell
        260. Pointers or references obtained from aliased smart pointers should not be used as function parameters

           Code Smell
        261. "try_lock", "lock" and "unlock" should not be directly used for mutexes

           Code Smell
        262. A single statement should not have more than one resource allocation

           Code Smell
        263. "#pragma pack" should be used correctly

           Bug
        264. Function parameters that are rvalue references should be moved

           Code Smell
        265. Capture by reference in lambdas used locally

           Code Smell
        266. Size of bit fields should not exceed the size of their types

           Code Smell
        267. Enums should be consistent with the bit fields they initialize

           Bug
        268. "pthread_mutex_t" should be unlocked in the reverse order they were locked

           Bug
        269. Only valid arguments should be passed to UNIX/POSIX functions

           Code Smell
        270. "pthread_mutex_t" should be properly initialized and destroyed

           Bug
        271. "pthread_mutex_t" should not be locked when already locked, or unlocked when already unlocked

           Bug
        272. Only valid arguments should be passed to stream functions

           Code Smell
        273. Using publicly writable directories is security-sensitive

           Security Hotspot
        274. "Forwarding references" parameters should be used only to forward parameters

           Code Smell
        275. Functions should not have more than one argument of type "bool"

           Code Smell
        276. Non-const global variables should not be used

           Code Smell
        277. The order for arguments of the same type in a function call should be obvious

           Code Smell
        278. "std::move" and "std::forward" should not be confused

           Bug
        279. "using" should be preferred for type aliasing

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

           Code Smell
        281. Classes should not contain both public and private data members

           Code Smell
        282. Functions that throw exceptions should not be used as hash functions

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

           Code Smell
        284. A call to "wait()" on a "std::condition_variable" should have a condition

           Bug
        285. "^" should not be confused with exponentiation

           Code Smell
        286. Each operand of the ! operator, the logical && or the logical || operators shall have type bool

           Bug
        287. A cast should not convert a pointer type to an integral type

           Code Smell
        288. An object with integral type or pointer to void type shall not be converted to an object with pointer type

           Code Smell
        289. An object with pointer type shall not be converted to an unrelated pointer type, either directly or indirectly

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

           Code Smell
        291. Using clear-text protocols is security-sensitive

           Security Hotspot
        292. The identifiers used for the parameters in a re-declaration or override of a function shall be identical to those in the declaration

           Code Smell
        293. using-directives and using-declarations (excluding class scope or function scope using-declarations) shall not be used in header files

           Code Smell
        294. A loop-control-variable other than the loop-counter shall not be modified within condition or expression

           Code Smell
        295. Blocking functions should not be called inside critical sections

           Code Smell
        296. The loop-counter shall not be modified within condition or statement

           Code Smell
        297. If loop-counter is not modified by -- or ++, then, within condition, the loop-counter shall only be used as an operand to <=, <, > or >=

           Code Smell
        298. A for loop shall contain a single loop-counter which shall not have floating type

           Code Smell
        299. Every switch statement shall have at least one case-clause

           Code Smell
        300. Return value of "setuid" family of functions should always be checked

           Code Smell
        301. All "if ... else if" constructs shall be terminated with an "else "clause

           Code Smell
        302. An `if ( condition )` construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement

           Code Smell
        303. The statement forming the body of a "switch", "while", "do {...} while" or "for" statement shall be a compound statement

           Code Smell
        304. C-style casts (other than void casts) and functional notation casts (other than explicit constructor calls) shall not be used

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

           Bug
        306. When an array is declared, its size shall either be stated explicitly or defined implicitly by initialization

           Bug
        307. GNU attributes should be used correctly

           Code Smell
        308. Format strings should comply with ISO standards

           Code Smell
        309. Size of variable length arrays should be greater than zero

           Code Smell
        310. Argument of "printf" should be a format string

           Code Smell
        311. "mktemp" family of functions templates should have at least six trailing "X"s

           Code Smell
        312. Unevaluated operands should not have side effects

           Code Smell
        313. Size argument of memory functions should be consistent

           Code Smell
        314. Return value of "nodiscard" functions should not be ignored

           Code Smell
        315. Implicit casts should not lower precision

           Code Smell
        316. "reinterpret_cast" should be used carefully

           Bug
        317. "std::move" should not inhibit optimizations

           Code Smell
        318. Appropriate size arguments should be passed to "strncat" and "strlcpy"

           Code Smell
        319. Moved-from objects should not be relied upon

           Code Smell
        320. Functions which do not return should be declared as "noreturn"

           Code Smell
        321. User-defined types should not be passed as variadic arguments

           Bug
        322. Class members should not be initialized with dangling references

           Bug
        323. Functions with "noreturn" attribute should not return

           Bug
        324. Keywords shall not be used as macros identifiers

           Code Smell
        325. Incomplete types should not be deleted

           Code Smell
        326. Logical operators should not be confused with bitwise operators

           Code Smell
        327. Dereferenced null pointers should not be bound to references

           Code Smell
        328. "else" statements should be clearly matched with an "if"

           Code Smell
        329. Header guards should be followed by a matching "#define" macro

           Code Smell
        330. Template parameters should be preferred to "std::function" when configuring behavior at compile time

           Code Smell
        331. Function pointers should not be used as function parameters

           Code Smell
        332. RAII objects should not be temporary

           Bug
        333. The addresses of standard library functions should not be taken

           Code Smell
        334. Expanding archive files without controlling resource consumption is security-sensitive

           Security Hotspot
        335. Macros should not be used to define constants

           Code Smell
        336. Memory should not be managed manually

           Code Smell
        337. Facilities in <random> should be used instead of "srand", "rand" and "random_shuffle"

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

           Code Smell
        339. Move and swap operations should be "noexcept"

           Code Smell
        340. "void *" should not be used in typedefs, member variables, function parameters or return type

           Code Smell
        341. "memcmp" should only be called with pointers to trivially copyable types with no padding

           Bug
        342. "memcpy", "memmove", and "memset" should only be called with pointers to trivially copyable types

           Bug
        343. Function parameters should not be of type "std::unique_ptr<T> const &"

           Code Smell
        344. "std::auto_ptr" should not be used

           Bug
        345. The "Rule-of-Zero" should be followed

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

           Code Smell
        347. Server certificates should be verified during SSL/TLS connections

           Vulnerability
        348. Using weak hashing algorithms is security-sensitive

           Security Hotspot
        349. "default" clauses should be first or last

           Code Smell
        350. Cryptographic keys should be robust

           Vulnerability
        351. Weak SSL/TLS protocols should not be used

           Vulnerability
        352. "auto" should not be used to deduce raw pointers

           Code Smell
        353. Include directives should not rely on non-portable search strategy

           Code Smell
        354. Methods should not have identical implementations

           Code Smell
        355. Array values should not be replaced unconditionally

           Bug
        356. Method overloads should be grouped together in the interface

           Code Smell
        357. A conditionally executed single line should be denoted by indentation

           Code Smell
        358. Conditionals should start on new lines

           Code Smell
        359. Integral operations should not overflow

           Bug
        360. "case" ranges should cover multiple values

           Code Smell
        361. "case" ranges should not be empty

           Bug
        362. All branches in a conditional structure should not have exactly the same implementation

           Bug
        363. Parameter values should be appropriate

           Bug
        364. "#include" paths should be portable

           Code Smell
        365. "#import" should not be used

           Code Smell
        366. Cognitive Complexity of functions should not be too high

           Code Smell
        367. Macros should not be redefined

           Code Smell
        368. Exceptions should not be thrown in "noexcept" functions

           Code Smell
        369. 'extern "C"' should not be used with namespaces

           Code Smell
        370. "auto" should not be used as a storage class specifier

           Code Smell
        371. "#include_next" should not be used

           Code Smell
        372. Array indices should be placed between brackets

           Code Smell
        373. String literals should not be concatenated implicitly

           Code Smell
        374. "extern" shouldn't be used on member definitions

           Bug
        375. Virtual functions should not have default arguments

           Code Smell
        376. GNU extensions should not be used

           Code Smell
        377. Reference types should not be qualified with "const" or "volatile"

           Code Smell
        378. Non-exception types should not be caught

           Code Smell
        379. Non-exception types should not be thrown

           Code Smell
        380. Comparison operators should not be virtual

           Code Smell
        381. Partial specialization syntax should not be used for function templates

           Code Smell
        382. Declaration specifiers should not be redundant

           Bug
        383. Local variables and member data should not be volatile

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

           Code Smell
        385. Alternative operators should not be used

           Code Smell
        386. Assignment operators should not be "virtual"

           Code Smell
        387. Member variables should not be "protected"

           Code Smell
        388. Destructors should be "noexcept"

           Bug
        389. Types and variables should be declared in separate statements

           Code Smell
        390. Scoped enumerations should be used

           Code Smell
        391. "const" and "volatile" should not be used in "enum" declarations

           Code Smell
        392. "reinterpret_cast" should not be used

           Code Smell
        393. Raw string literals should be used

           Code Smell
        394. Classes should have regular copy and move semantic

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

           Code Smell
        396. Default capture should not be used

           Code Smell
        397. Stack allocated memory and non-owned memory should not be freed

           Bug
        398. Closed resources should not be accessed

           Bug
        399. Dynamically allocated memory should be released

           Bug
        400. "final" classes should not have "virtual" functions

           Code Smell
        401. Redundant lambda return types should be omitted

           Code Smell
        402. "switch" statements should cover all cases

           Code Smell
        403. "inline" should not be used redundantly

           Code Smell
        404. Declarations of functions defined outside of the class should not be marked as "inline"

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

           Code Smell
        406. Digit separators should be used

           Code Smell
        407. Allocation and deallocation functions should not be explicitly declared "static"

           Code Smell
        408. Base class access specifiers should not be redundant

           Code Smell
        409. Access specifiers should not be redundant

           Code Smell
        410. Freed memory should not be used

           Bug
        411. The "register" storage class specifier should not be used

           Code Smell
        412. Memory locations should not be released more than once

           Bug
        413. Memory access should be explicitly bounded to prevent buffer overflows

           Bug
        414. Zero should not be a possible denominator

           Bug
        415. Redundant pointer operator sequences should be removed

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

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

           Code Smell
        418. Standard namespaces should not be modified

           Code Smell
        419. Inheritance should be "public"

           Code Smell
        420. Function declarations that look like variable declarations should not be used

           Bug
        421. Empty "case" clauses that fall through to the "default" should be omitted

           Code Smell
        422. Format strings should be used correctly

           Code Smell
        423. Destructors should not be called explicitly

           Code Smell
        424. Conditional operators should not be nested

           Code Smell
        425. Namespaces should not be empty

           Code Smell
        426. "static" base class members should not be accessed via derived types

           Code Smell
        427. Forward declarations should not be redundant

           Code Smell
        428. Member data should be initialized in-class or in a constructor initialization list

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

           Code Smell
        430. Label names should comply with a naming convention

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

           Bug
        432. "this" should not be compared with null

           Code Smell
        433. "const" references to numbers should not be made

           Bug
        434. The "delete" operator should only be used for pointers

           Code Smell
        435. Binary operators should be overloaded as hidden friend functions

           Code Smell
        436. Bit fields should not be used

           Code Smell
        437. Unary prefix operators should not be repeated

           Bug
        438. Non-existent operators like "=+" should not be used

           Bug
        439. XML parsers should not be vulnerable to XXE attacks

           Vulnerability
        440. Declarations should not be empty

           Code Smell
        441. Values of different "enum" types should not be compared

           Bug
        442. General "catch" clauses should not be used

           Code Smell
        443. "catch" clauses should do more than rethrow

           Code Smell
        444. Multiline blocks should be enclosed in curly braces

           Code Smell
        445. Increment should not be used to set boolean variables to 'true'

           Code Smell
        446. The "sizeof" and "alignof" operator should not be used with operands of a "void" type

           Bug
        447. "nonnull" parameters and return values of "returns_nonnull" functions should not be null

           Bug
        448. Setting loose POSIX file permissions is security-sensitive

           Security Hotspot
        449. Conditionally executed code should be reachable

           Bug
        450. Exceptions should not be ignored

           Code Smell
        451. Control characters should not be used in literals

           Code Smell
        452. Child class fields should not shadow parent class fields

           Code Smell
        453. Enumeration values should comply with a naming convention

           Code Smell
        454. Enumeration names should comply with a naming convention

           Code Smell
        455. Octal and hexadecimal escape sequences should be terminated

           Code Smell
        456. Flexible array members should not be declared

           Code Smell
        457. Line-splicing should not be used in "//" comments

           Bug
        458. Standard C++ headers should be used

           Code Smell
        459. Namespace names should comply with a naming convention

           Code Smell
        460. Exception specifications should not be used

           Code Smell
        461. Printf-style format strings should not lead to unexpected behavior at runtime

           Bug
        462. Track parsing failures

           Code Smell
        463. Null pointers should not be dereferenced

           Bug
        464. User-specified functions should not be called

           Code Smell
        465. Using pseudorandom number generators (PRNGs) is security-sensitive

           Security Hotspot
        466. Parameters should be passed in the correct order

           Code Smell
        467. Single-bit named bit fields should not be of a signed type

           Bug
        468. "static" members should be accessed statically

           Code Smell
        469. "for" loop counters should not have essentially floating type

           Bug
        470. Recursion should not be infinite

           Bug
        471. "final" classes should not have "protected" members

           Code Smell
        472. Values should not be uselessly incremented

           Bug
        473. Member variables should be initialized

           Bug
        474. Resources should be closed

           Bug
        475. Hard-coded passwords are security-sensitive

           Security Hotspot
        476. "final" should not be used redundantly

           Code Smell
        477. Comment styles "//" and "/* ... */" should not be mixed within a file

           Code Smell
        478. Line continuation characters '\' should not be followed by trailing whitespace

           Bug
        479. Preprocessor directives should not be indented

           Code Smell
        480. Track instances of the "#error" preprocessor directive being reached

           Code Smell
        481. "sizeof(sizeof(...))" should not be used

           Bug
        482. Non-reentrant POSIX functions should be replaced with their reentrant versions

           Code Smell
        483. Obsolete POSIX functions should not be used

           Code Smell
        484. "goto" statements should not be used to jump into blocks

           Code Smell
        485. Redundant casts should not be used

           Code Smell
        486. "union" names should comply with a naming convention

           Code Smell
        487. Code annotated as deprecated should not be used

           Code Smell
        488. Two branches in a conditional structure should not have exactly the same implementation

           Code Smell
        489. Related "if/else if" statements should not have the same condition

           Bug
        490. Unused assignments should be removed

           Code Smell
        491. "switch" statements should not be nested

           Code Smell
        492. Structures should not have too many fields

           Code Smell
        493. The ternary operator should not be used

           Code Smell
        494. "public", "protected" and "private" sections of a class should be declared in that order

           Code Smell
        495. Constants should come first in equality tests

           Code Smell
        496. A "struct" should not have member functions

           Code Smell
        497. The sign of an unsigned variable should not be tested

           Code Smell
        498. Pointers should not be cast to integral types

           Bug
        499. Identical expressions should not be used on both sides of a binary operator

           Bug
        500. All code should be reachable

           Bug
        501. "#pragma warning (default: ...)" should not be used

           Code Smell
        502. Pre-defined macros should not be defined, redefined or undefined

           Code Smell
        503. Keywords introduced in later specifications should not be used as identifiers

           Code Smell
        504. Loops with at most one iteration should be refactored

           Bug
        505. Lambdas should not be used

           Code Smell
        506. Type specifiers should be listed in a standard order

           Code Smell
        507. Default parameters should not be defined

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

           Code Smell
        509. C++ comments should be used

           Code Smell
        510. Track "TODO" and "FIXME" comments that do not contain a reference to a person

           Code Smell
        511. Exceptions should not be used

           Code Smell
        512. The prefix increment/decrement form should be used

           Code Smell
        513. Virtual functions should not be called from constructors or destructors

           Code Smell
        514. The original exception object should be rethrown

           Bug
        515. Context-sensitive keywords should not be used as identifiers

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

           Code Smell
        517. Variables should not be self-assigned

           Bug
        518. "struct" names should comply with a naming convention

           Code Smell
        519. File names should comply with a naming convention

           Code Smell
        520. Macro names should comply with a naming convention

           Code Smell
        521. Cyclomatic Complexity of functions should not be too high

           Code Smell
        522. Unused local variables should be removed

           Code Smell
        523. "switch" statements should not have too many "case" clauses

           Code Smell
        524. Track lack of copyright and license headers

           Code Smell
        525. Classes should not have too many methods

           Code Smell
        526. Comments should not be located at the end of lines of code

           Code Smell
        527. Functions/methods should not have too many lines

           Code Smell
        528. Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply

           Code Smell
        529. Octal values should not be used

           Code Smell
        530. Using hardcoded IP addresses is security-sensitive

           Security Hotspot
        531. "switch" statements should have "default" clauses

           Code Smell
        532. "if" statements should be preferred over "switch" when simpler

           Code Smell
        533. Track uses of "NOSONAR" comments

           Code Smell
        534. Switch cases should end with an unconditional "break" statement

           Code Smell
        535. "::" operator should be used to access global variables and functions

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

           Code Smell
        537. "for" loop stop conditions should be invariant

           Code Smell
        538. "operator delete" should be written along with "operator new"

           Bug
        539. A "while" loop should be used instead of a "for" loop

           Code Smell
        540. "if ... else if" constructs should end with "else" clauses

           Code Smell
        541. "typedef" should be used for function pointers

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

           Code Smell
        543. Floating point numbers should not be tested for equality

           Bug
        544. Inherited functions should not be hidden

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

           Code Smell
        546. Assignment operators should return non-"const" reference to the assigned object

           Code Smell
        547. Polymorphic base class destructor should be either public virtual or protected non-virtual

           Code Smell
        548. Appropriate memory de-allocation should be used

           Bug
        549. C-style memory allocation routines should not be used

           Code Smell
        550. break statements should not be used except for switch cases

           Code Smell
        551. Statements should be on separate lines

           Code Smell
        552. "switch" statements should not contain non-case labels

           Code Smell
        553. Control structures should use curly braces

           Code Smell
        554. Nested code blocks should not be used

           Code Smell
        555. Lambdas should not have too many lines

           Code Smell
        556. Methods should not be empty

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

           Code Smell
        558. Generic exceptions should not be caught

           Code Smell
        559. Unused function parameters should be removed

           Code Smell
        560. Local variable and function parameter names should comply with a naming convention

           Code Smell
        561. Field names should comply with a naming convention

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

           Code Smell
        563. "switch case" clauses should not have too many lines of code

           Code Smell
        564. Unused functions and methods should be removed

           Code Smell
        565. Functions should not contain too many return statements

           Code Smell
        566. Try-catch blocks should not be nested

           Code Smell
        567. Track uses of "TODO" tags

           Code Smell
        568. Track uses of "FIXME" tags

           Code Smell
        569. Deprecated code should be removed

           Code Smell
        570. Lines should not end with trailing whitespaces

           Code Smell
        571. Files should end with a newline

           Code Smell
        572. Deprecated attributes should include explanations

           Code Smell
        573. Assignments should not be made from within conditions

           Code Smell
        574. Generic exceptions should never be thrown

           Code Smell
        575. Variables should not be shadowed

           Code Smell
        576. Empty statements should be removed

           Code Smell
        577. Redundant pairs of parentheses should be removed

           Code Smell
        578. "/*" and "//" should not be used within comments

           Code Smell
        579. Inheritance tree of classes should not be too deep

           Code Smell
        580. Magic numbers should not be used

           Code Smell
        581. Insecure functions should not be used

           Vulnerability
        582. Nested blocks of code should not be left empty

           Code Smell
        583. "scanf()" and "fscanf()" format strings should specify a field width for the "%s" string placeholder

           Vulnerability
        584. Functions should not have too many parameters

           Code Smell
        585. Unused "private" fields should be removed

           Code Smell
        586. Expressions should not be too complex

           Code Smell
        587. Mergeable "if" statements should be combined

           Code Smell
        588. Unused labels should be removed

           Code Smell
        589. Standard outputs should not be used directly to log anything

           Code Smell
        590. "<cstdio>" should not be used

           Code Smell
        591. "<ctime>" should not be used

           Code Smell
        592. C libraries should not be used

           Code Smell
        593. Tabulation characters should not be used

           Code Smell
        594. Destructors should not throw exceptions

           Bug
        595. Condition-specific "catch" handlers should not be used after the ellipsis (catch-all) handler

           Bug
        596. 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
        597. Exception classes should be caught by reference

           Bug
        598. Handlers of a function-try-block implementation of a class constructor or destructor shall not reference non-static members from this class or its bases

           Bug
        599. Files should not have too many lines of code

           Code Smell
        600. Empty throws ("throw;") should only be used in the compound statements of catch handlers

           Bug
        601. Control should not be transferred into a complex logic block using a "goto" or a "switch" statement

           Code Smell
        602. An exception object should not have pointer type

           Bug
        603. Function templates should not be specialized

           Code Smell
        604. Lines should not be too long

           Code Smell
        605. Pure "virtual" functions should not override non-pure "virtual" functions

           Code Smell
        606. Virtual functions should be declared with the "virtual" keyword

           Code Smell
        607. Accessible base classes should not be both "virtual" and non-virtual in the same hierarchy

           Bug
        608. Classes should not be derived from virtual bases

           Code Smell
        609. Class names should comply with a naming convention

           Code Smell
        610. Parameters in an overriding virtual function shall either use the same default arguments as the function they override, or else shall not specify any default arguments

           Code Smell
        611. A function should have a single point of exit at the end of the function

           Code Smell
        612. "using namespace" directives should not be used in header files

           Code Smell
        613. Multiple declarations for an identifier in the same namespace shall not straddle a using-declaration for that identifier

           Bug
        614. "using-directives" should not be used

           Code Smell
        615. Header files should not contain unnamed namespaces

           Code Smell
        616. Function names should comply with a naming convention

           Code Smell
        617. The character handling functions from "<cctype>" and "<cwctype>" shall not be used

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

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

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

           Code Smell
        621. "Global variables" shall not be used

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

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

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

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

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

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

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

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

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

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

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

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

           Bug
        634. All variables should be initialized

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

           Bug
        636. An object shall not be used while in a "potentially moved-from state"

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

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

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

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

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

           Code Smell
        642. The standard "header file" "<csetjmp>" shall not be used

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

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

           Bug
        645. A "noexcept" function should not attempt to propagate an exception to the calling function

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

           Bug
        647. 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
        648. An "empty throw" shall only occur within the "compound-statement" of a "catch handler"

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

           Bug
        650. Classes should not be inherited virtually

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

           Bug
        652. The "union" keyword shall not be used

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

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

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

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

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

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

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

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

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

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

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

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

           Code Smell
        665. "nullptr" shall be the only form of the "null-pointer-constant"

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

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

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

           Bug
        669. Tokens that look like a preprocessing directive shall not occur within a macro argument

           Bug
        670. Function-like macros shall not be defined

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

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

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

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

           Code Smell

        Variables should not be shadowed

        intentionality - clear
        maintainability
        Code Smell
        • based-on-misra
        • cert
        • suspicious
        • pitfall

        Why is this an issue?

        More Info

        Variable shadowing happens when a variable declared in a specific scope has the same name as a variable in an outer scope.

        This can lead to three main problems:

        • Confusion: The same name can refer to different variables in different parts of the scope, making the code hard to read and understand.
        • Unintended Behavior: You might accidentally use the wrong variable, leading to hard-to-detect bugs.
        • Maintenance Issues: If the inner variable is removed or renamed, the code’s behavior might change unexpectedly because the outer variable is now being used.

        To avoid these problems, rename the shadowing, shadowed, or both variables to accurately represent their purpose with unique and meaningful names.

        The examples below show typical situations in which shadowing can occur.

        • Parameter shadowing
          void f(int x, bool b) {
            int y = 4;
            if (b) {
              int x = 7; // Noncompliant: the parameter "x" is shadowed.
              int y = 9; // Noncompliant: the local variable "y" is shadowed.
              // ...
            }
          }
          
        • Member variable shadowing
          class Foo {
          private:
            int myField;
          
          public:
            void doSomething() {
              int myField = 0; // Noncompliant: Foo::myField is shadowed.
              // ...
            }
          };
          
        • Global variable shadowing
          namespace ns {
            int state;
          
            void bar() {
              int state = 0; // Noncompliant: the namespace variable is shadowed.
            }
          }
          

        Exceptions

        It is common practice to have constructor arguments shadowing the fields they initialize in the member initializer list. This pattern avoids the need to select new names for the constructor arguments and will not be reported by this rule.

        class Point {
        public:
          Point(int x, int y)
            : x(x) // Compliant by exception: the parameter "x" is used
                   // in the member initializer list.
          {
            y = y; // Noncompliant: the parameter is assigned to itself
                   // and the member "y" is not initialized.
          }
        
        private:
          int x;
          int y;
        };
        

        Caveats

        Shadowing in if, else if, and else

        Variables can be introduced in the condition of an if statement. Their scope includes the optional else statement, which may be surprising. Consequently, such variables can be shadowed in an else if statement. This can be even more confusing and result in unintended behavior, as illustrated in this example:

        using ExpectedData = std::expected<std::string, std::error_code>;
        
        if (ExpectedData e = readData()) {
          printMessage(e.value());
        } else if (ExpectedData e = readFallbackSource()) { // Noncompliant
          printMessage(e.value());
        } else {
          logError(
            "Initial source failed with: ",
            e.error() // Contrary to the intention, the second "e" is used.
          );
        }
        

        Shadowing of inaccessible declarations

        This rule also raises issues on some variables, although they do not shadow another variable according to a strict interpretation of the C++ language. There are mainly two reasons for this.

        1. Primarily, the readability and maintainability of the code are impaired. Readers need an advanced understanding of the C++ language to understand the subtle differences.
        2. Secondly, a small change can lead to actual shadowing. This can lead to subtle bugs when updating the code.

        Here is an example with nested classes:

        class A {
        public:
          int x;
          class B;
        };
        
        class A::B {
          void f(int x) { // Noncompliant: The parameter "x" shadows the field "A::x".
            // ...
          }
        };
        

        In the above example, A::x cannot be used from A::B member functions because it is not a static field. This can lead to surprising effects when moving code around, particularly if the declaration of A::x was changed from int x; to static int x;.

        You should always avoid shadowing to avoid any confusion and increase the maintainability of your code.

          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
          Developer Edition
          Available Since
          9.1

        © 2008-2025 SonarSource SA. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use