Main Content

CERT C: Rec. PRE02-C

Macro replacement lists should be parenthesized

Since R2026a

Description

Macro replacement lists should be parenthesized1

Polyspace Implementation

Polyspace checks for these issues:

  • Incorrect Macro Expansion

Examples

expand all

Issue

The issue occurs when a macro expansion is not parenthesized to preserve the order of operation. Violations are not reported if the macro expands to any of these:

  • Function calls,

  • Array item access,

  • Structure member access using -> or . operators.

Risk

If the replacement list is not parenthesized, surrounding operators may bind differently than intended, producing incorrect results, unexpected precedence interactions, or logic errors. In safety- or security-critical code these can produce incorrect behavior or vulnerabilities.

Fix

To fix this issue, parenthesize macro expansions.

Example

In this example the CUBE macro replacement list is not fully parenthesized, so its use in 81 / CUBE(i) leads to incorrect grouping.

#define CUBE(X) (X) * (X) * (X)  // Noncompliant

void foo() {
	int i = 3;
	int a = 81 / CUBE(i);  // expands to 81 / (i) * (i) * (i) which is parsed as (81 / i) * i * i
}
Correction

Enclose the entire replacement list in parentheses so the macro expands to a single expression with correct precedence.

#define CUBE(X) ((X) * (X) * (X))  // Compliant

void foo() {
	int i = 3;
	int a = 81 / CUBE(i);// expands to 81 / ((i) * (i) * (i)) as intended
}

Check Information

Group: Rec. 01. Preprocessor (PRE)
PQL Name: std.cert.PRE02_C

Version History

Introduced in R2026a


1 This software has been created by MathWorks incorporating portions of: the “SEI CERT-C Website,” © 2017 Carnegie Mellon University, the SEI CERT-C++ Web site © 2017 Carnegie Mellon University, ”SEI CERT C Coding Standard – Rules for Developing safe, Reliable and Secure systems – 2016 Edition,” © 2016 Carnegie Mellon University, and “SEI CERT C++ Coding Standard – Rules for Developing safe, Reliable and Secure systems in C++ – 2016 Edition” © 2016 Carnegie Mellon University, with special permission from its Software Engineering Institute.

ANY MATERIAL OF CARNEGIE MELLON UNIVERSITY AND/OR ITS SOFTWARE ENGINEERING INSTITUTE CONTAINED HEREIN IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.

This software and associated documentation has not been reviewed nor is it endorsed by Carnegie Mellon University or its Software Engineering Institute.