Main Content

Use of a forbidden C/C++ keyword

Use of keyword that appears in a blocklist of forbidden keywords

Since R2022a

Description

This defect occurs when you use a keyword that appears in a blocklist of forbidden keywords. To create the blocklist:

  • List keywords in an XML file in a specific syntax.

    Copy the template file code-behavior-specifications-template.xml from the folder polyspaceroot\polyspace\verifier\cxx to a writable location and modify the file. Enter each keyword in the file using the following syntax after existing similar entries:

    <token name="keywordname" kind="keyword">
          <behavior name="FORBIDDEN_KEYWORD"/>
    </token>
    where keywordname is the name of the keyword you want to block.

  • Specify this XML file as argument for the option -code-behavior-specifications. See Flag Deprecated or Unsafe Functions, Keywords, or Macros Using Bug Finder Checkers.

The checker can be used to forbid keywords with whitespaces such as for each or enum class.

Risk

A keyword might be blocked for one of these reasons:

  • The keyword is prone to misuse or makes the code difficult to maintain.

  • The keyword is being deprecated as part of a migration, for instance, from C++98 to C++11.

    As part of a migration, you can make a list of keywords that need to be replaced and use this checker to identify their use.

Fix

Replace the blocked keyword with an allowed keyword.

When rolling out this checker to a group, project or organization, create a list of blocked keywords and their replacements so that results reviewers can consult the list and make appropriate replacements.

Extend Checker

This defect checker requires a blocklist of keywords to be specified. Even if you specify the checker using the option Find defects (-checkers), it is not enabled unless you also specify the blocklist. See Flag Deprecated or Unsafe Functions, Keywords, or Macros Using Bug Finder Checkers.

Examples

expand all

class Base {
public:
    virtual bool isThisFinal() const {
        return false;
    }
};
class final : public Base {
    virtual bool isThisFinal() const
    override
    final {
        return true;
    }
};

Suppose you want to deprecate the final keyword. Add the following to the template XML file after similar existing entries:

<?xml version="1.0" encoding="UTF-8"?>
<specifications xmlns="http://www.mathworks.com/PolyspaceCodeBehaviorSpecifications">
  <tokens>
    <token name="final" kind="keyword">
       <behavior name="FORBIDDEN_KEYWORD"/>
    </token>
  </tokens>
</specifications>
and specify the XML file with the option -code-behavior-specifications.

In the analysis results, all uses of the final keyword are flagged by this checker. Note that the checker flags only the keyword final and not the class name final.

Result Information

Group: Good practice
Language: C | C++
Default: Off
Command-Line Syntax: FORBIDDEN_KEYWORD
Impact: Low

Version History

Introduced in R2022a