diff --git a/rules/S6004/cfamily/metadata.json b/rules/S6004/cfamily/metadata.json index 6ee4cc4726..8c4ffb9089 100644 --- a/rules/S6004/cfamily/metadata.json +++ b/rules/S6004/cfamily/metadata.json @@ -1,5 +1,5 @@ { - "title": "\"if\",\"switch\", and range-based for loop initializer should be used to reduce scope of variables", + "title": "\"if\" and \"switch\" initializer should be used to reduce scope of variables", "type": "CODE_SMELL", "code": { "impacts": { diff --git a/rules/S6004/cfamily/rule.adoc b/rules/S6004/cfamily/rule.adoc index 316a1c3e81..85e766948e 100644 --- a/rules/S6004/cfamily/rule.adoc +++ b/rules/S6004/cfamily/rule.adoc @@ -36,7 +36,7 @@ bool better_init() { This rule raises an issue when: -- a variable is declared just before a statement that allows variable declaration (`if`, `switch`, or, starting {cpp}20, range-based `for` loop), +- a variable is declared just before a statement that allows variable declaration (`if`, `switch`), - this variable is used in the statement header, - there are other statements after this statement where this variable might be used, - yet, it is never used after the statement. @@ -82,32 +82,6 @@ void switchStatement() { } ---- -[source,cpp] ----- -std::vector> getTable(); -void printHeadersBad() { - auto rows = getTable(); // Noncompliant in C++20: rows is accessible outside of the loop - for (int x : rows[0]) { - std::cout << x <<' '; - } - std::cout << "\n"; -} ----- - -Using a temporary to avoid leaking of the variable into the ambient scope creates a bigger problem: an undefined behavior. Even though the lifetime of a temporary returned by the range expression is extended, the life of a temporary within the range expression terminates before the loop begins to execute. - -[source,cpp] ----- -std::vector> getTable(); -void printHeadersWorse() { - for (int x : getTable()[0]) { // Undefined behavior: return value of getTable() no longer exists in the loop body - std::cout << x <<' '; - } - std::cout << "\n"; -} ----- - - === Compliant solution [source,cpp] @@ -141,15 +115,6 @@ void switchStatement() { } std::cout << "\n"; } - -std::vector> getTable(); -void printHeadersGood() { - // Compliant: rows is accessible only inside the loop (this code requires at least C++20) - for (auto rows = getTable(); int x : table[0]) { - std::cout << x <<' '; - } - std::cout << "\n"; -} ---- === Exceptions