Main Content

MISRA C++:2023 Rule 19.0.2

Function-like macros shall not be defined

Since R2024b

Description

Rule Definition

Function-like macros shall not be defined.

Rationale

Using functions has certain advantages over using function-like macros. For example:

  • You can pass a function address to another function.

  • You can overload functions and create templates.

  • Type checking is performed on function arguments and return values.

For a full list of advantages of using functions over macros, see the MISRA-C++:2023 standard.

Polyspace Implementation

Polyspace® reports a rule violation whenever a function-like macro is defined. The following are exceptions to the rule when used in the macro definition as their equivalent behavior is not possible to implement in a function:

  • __LINE__

  • __FILE__

  • __func__

  • The # or ## operators

Polyspace does not report a violation when a function-like macro is defined as (void)(X). These kinds of macros are typically used with a function as an input. For example, you can use such a macro to explicitly cast the return value of a function to void. The use of this macro cannot be replicated by a function.

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

#define MAX(a, b) ((a) > (b) ? (a) : (b))           //Noncompliant
#define UNUSED(X) (void)(X)                         //Compliant
#define MSG(msg) printf("%d:%s\n",__LINE__,msg);    //Compliant

int main() {
    int x = 5;
    int y = 10;
    int max = MAX(x, y);

    return 0;
}

Because the code defines the function-like macro MAX and MAX does not contain one of the exceptions, Polyspace reports a rule violation. Replace MAX with a function to comply with the rule.

The macro MSG is compliant with the rule because it uses the __LINE__ preprocessor macro. are compliant by exception. The macro UNUSED(X) is compliant by exception because it is defined as (void)(X).

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2024b