主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

CERT C:Rec.PRE03-C

Prefer typedefs to defines for encoding non-pointer type

自 R2024a 起

描述

规则定义

Prefer typedefs to defines for encoding non-pointer type.1

Polyspace 实现

规则检查项检查问题宏中编码了非指针类型

示例

全部展开

问题

当非指针类型使用 #define 预处理器指令而不是 typedef 编码为宏时,会发生此问题。在以下情况下,规则检查器不会报告违规:

  • 指针类型通过宏进行编码。

  • 您在宏中与类型一起编码修饰符,例如 staticvolatile。这些修饰符不属于类型定义的一部分,因此无法在 typedef 语句中使用。

  • 在代码中未使用用于编码非指针类型的宏。

风险

宏定义不遵循作用域规则,宏中编码的类型通过文本替换应用于代码。最佳做法是使用 typedef 类型对非指针类型进行编码。

修复

使用 typedef 编码非指针类型,而不是使用宏。

示例 - 在宏中编码的类型

在此示例中,规则检查器报告了对编码非指针类型的宏的违规情况。

#define MATRIX(X) double X[4][4]  //Noncompliant
#define MY_INTEGRAL_TYPE1(sign, base) sign base  //Noncompliant
#define QUAL_TYPE_MAC1 const int  //Unused - no violation reported
#define QUAL_TYPE_MAC3 static volatile int //Not a violation
                  // - volatile and static cannot be used with typedefs

void noncompliant ()
{
    MATRIX(tab);
	MY_INTEGRAL_TYPE1(unsigned, int) uint;
	QUAL_TYPE_MAC3 var3;
}

未使用的宏以及编码了修饰符(如 volatilestatic)的宏不违反此规则。

更正 - 使用 typedef 声明来编码非指针类型

在此合规示例中,非指针类型使用 typedef 语句进行编码。

typedef double matrix[4][4];
typedef unsigned int myint;

void compliant ()
{
    matrix matrix_a;
	myint uint;
}

检查信息

组:Rec.01.预处理器 (PRE)

版本历史记录

在 R2024a 中推出


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.