Main Content

AUTOSAR C++14 Rule M16-1-1

The defined pre-processor operator shall only be used in one of the two standard forms

Description

Rule Definition

The defined pre-processor operator shall only be used in one of the two standard forms.

Rationale

The defined preprocessor operator checks whether an identifier is defined as a macro. In C, the only two permissible forms for this operator are:

  • defined (identifier)

  • defined identifier

Using any other form results in invalid code that compiler might not report. For instance, if you use expressions as arguments for the defined operator, the code is invalid. If the compiler does not report the invalid usage of defined, diagnosing the invalid code is difficult.

If your #if or similar preprocessor directives expand to create a defined statement, the code behavior is undefined. For instance:

#define DEFINED defined
#if DEFINED(X)
The #if preprocessor directive expands to form a defined operation. Depending on your environment, the code might behave in unexpected ways, leading to bugs that are difficult to diagnose.

To avoid invalid code, bugs, and undefined behavior, use only the permitted forms when using the defined operator.

Polyspace Implementation

Polyspace® flags incorrect usages of the defined operator, such as:

  • The operator defined is used without an identifier.

  • The operator defined appears after macro expansion.

  • The operator defined is used with a complex expression.

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

#if defined (X<Y)//Noncompliant
//...
#endif
#if defined (X) && defined (Y) &&(X<Y)//Compliant
//...
#endif

In this example, a block of code is conditionally executed only if the identifiers X and Y are defined and if X is smaller than Y. Constructing this condition by using an expression as the argument for the defined operator is not permissible and results in invalid code. Polyspace flags the impermissible defined statement. The permissible way to define such a condition is to use individual identifiers with defined.

Check Information

Group: Preprocessing Directives
Category: Required, Automated

Version History

Introduced in R2019a