主要内容

MISRA C:2023 Rule 23.3

A generic selection should contain at least one non-default association

自 R2024a 起

描述

规则定义

A generic selection should contain at least one non-default association 1 .

此规则来自 MISRA C™:2012 Amendment 3。

理由

当无法选择任何非默认关联时,将会选择泛型选择的 default 关联且不会进行任何类型检查。仅包含一个 default 关联的 _Generic 语句始终会选择该 default 选择项,因此没有实际作用。

应在泛型选择中包含至少一个非默认关联。如果您打算在泛型选择中类型不匹配时引入约束违反值,请省略 default 关联。

Polyspace 实现

如果 _Generic 语句仅包含 default 关联,则 Polyspace® 会报告违反了此规则。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

在示例中,_Generic 语句 get_type_id_only_default 仅包含一个 default 关联。在函数 foo() 中,用任何类型调用此 _Generic 语句都会导致选择 default 关联。此泛型选择没有实际作用,Polyspace 会报告违规。

 #define get_type_id(x) ( _Generic((x) /* Compliant */ \
                                , char : 0       \
                                , int  : 1       \
                                ))

#define get_type_id_with_default(x) ( _Generic((x) /* Compliant */ \
                                , char : 0       \
                                , int  : 1       \
                                , default : 3    \
                                ))

#define get_type_id_only_default(x) ( _Generic((x) /* Noncompliant */ \
                                , default : -1   \
                                ))

void foo() {
    int x, y;
    y = get_type_id(x);
    y = get_type_id_with_default(x);
    y = get_type_id_only_default(x);
}

_Generic 语句 get_type_idget_type_id_with_default 包含非默认关联,Polyspace 不会报告违规。

检查信息

组:泛型选择
类别:建议
AGC 类别:建议

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.