Main Content

AUTOSAR C++14 Rule A2-7-2

Sections of code shall not be "commented out"

Since R2020b

Description

Rule Definition

Sections of code shall 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. 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. For instance, characters such as #, ;, { or } indicate comments that might potentially contain code. These comments are then evaluated against other metrics to determine the likelihood of code masquerading as comment. For instance, several successive words without a symbol in between reduces this likelihood.

The checker does not flag the following comments even if they contain code:

  • Doxygen comments beginning with /**, /*!, /// or //!.

  • Comments that repeat the same symbol several times, for instance, the symbol = here:

    // =====================================
    // A comment
    // =====================================*/

  • Comments on the first line of a file.

  • Comments that mix the C style (/* */) and C++ style (//).

The checker considers that these comments are meant for documentation purposes or entered deliberately with some forethought.

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 <iostream>
/* class randInt { //Noncompliant
    public: 
      int getRandInt();
};
*/

int getRandInt();

/* Function to print random integers*/ 
void printInteger() {
    /* int val = getRandInt(); //Noncompliant
     * val++; 
     * std::cout << val;*/     
    std::cout << getRandInt();
}

This example contains two blocks of commented out code, that constitutes two rule violations.

#include <iostream>
int getRandInt();

// Function to print random integers
void printInteger() {
    // int val = getRandInt(); //Noncompliant
    // val++; 
    // std::cout << val;     
    std::cout << getRandInt();
}

This example contains a block of commented out code that violates the rule.

Check Information

Group: Lexical Conventions
Category: Required, Non-automated

Version History

Introduced in R2020b

expand all