Main Content

MISRA C++:2023 Dir 5.7.2

Sections of code should not be "commented out"

Since R2024b

Description

Rule Definition

Sections of code should not be "commented out".

Rationale

Commenting out code is not a good practice. The commented out code can remain out of sync with the surrounding code without causing compilation errors. Later, if you uncomment the code, you can encounter unexpected issues.

In addition, C-style comments enclosed in /* */ do not support nesting on all implementations. A comment beginning with /* ends at the first */ even when the */ is intended as the end of a later nested comment. If a section of code that is commented out already contains comments, you can encounter compilation errors (or at least comment out less code than you intend).

Use comments only to explain aspects of the code that are not apparent from the code itself.

Polyspace Implementation

The checker uses internal heuristics to detect commented out code and report a violation. The violation is reported once per block of commented out code. The checker allows comment out code that is wrapped between two occurrences of ```.

In addition to commented out code, the checker also reports a violation on code deactivated using #if 0.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <vector>
#include <optional>

// Get item from integer list - Noncompliant
// std::optional<int> getIntegerItemFromList(const std::vector<int>& list, int item) {
//    for (const auto& listItem : list) {
//        if (listItem == item) {
//            return listItem;
//        }
//    }
//    return std::nullopt;
// }

// Get item from character list - Compliant
// ```
// std::optional<int> getCharacterItemFromList(const std::vector<int>& list, int item) {
//    for (const auto& listItem : list) {
//        if (listItem == item) {
//            return listItem;
//        }
//    }
//    return std::nullopt;
// }
// ```


template <typename T>
std::optional<T> getItemFromList(const std::vector<T>& list, const T& item) {
    for (const auto& listItem : list) {
        if (listItem == item) {
            return listItem;
        }
    }
    return std::nullopt;
}

In this example, the first block of comment contains code and violates the rule. The second block includes code wrapped in ``` and does not violate the rule.

Check Information

Group: Lexical Conventions
Category: Advisory

Version History

Introduced in R2024b