Main Content

MISRA C++:2023 Rule 19.0.4

#undef should only be used for macros defined previously in the same file

Since R2024b

Description

Rule Definition

#undef should only be used for macros defined previously in the same file.

Rationale

Using #undef in the same file as the macro definition limits the scope of macros, minimizing conflicts and unintentional consequences due to use of macros defined in other files. Following this guideline also promotes better code organization by defining and undefining each macro in a single file, making code easier to read and maintain.

Polyspace Implementation

Polyspace® reports a rule violation whenever a macro is undefined in a file where it is not also defined.

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

The header file macros.h defines these macros.

#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))

The file Source.cpp includes the macro definitions from macros.h.

#include <iostream>

#include "macros.h"              //Import macros MAX and PI from file "macros.h"
#undef PI                     //Noncompliant
#define MIN(a, b) ((a) < (b) ? (a) : (b))

int findMax() {
    int x = 5;
    int y = 10;

    int max = MAX(x, y); 

    std::cout << "The maximum value is: " << max << std::endl;

    double radius = 5.0;
    double circumference = 2 * PI * radius;

    std::cout << "The circumference of the circle is: " << circumference << std::endl;

    return 0;
}
#undef MAX                     //Noncompliant
#undef MIN                     //Compliant

Because the macros PI and MAX defined in macros.h are undefined in Source.cpp, Polyspace reports the #undef statements for PI and MAX in Source.cpp as noncompliant.

Because the macro MIN is defined and undefined within the same file, it is compliant.

Check Information

Group: Preprocessing Directives
Category: Advisory

Version History

Introduced in R2024b