Main Content

MISRA C:2012 Rule 23.3

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

Since R2024a

Description

Rule Definition

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

This rule comes from MISRA C™: 2012 Amendment 3.

Rationale

The default association of a generic selection is selected without any type checking when none of the nondefault associations can be selected. A _Generic statement that consists of only a default association always selects the default selection and is not useful.

Include at-least one nondefault association in a generic selection. If you intend to introduce a constraint violation when the types do not match in a generic selection, omit the default association.

Polyspace Implementation

Polyspace® reports a violation of this rule if a _Generic statement contains only the default association.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In the example, the _Generic statement get_type_id_only_default consists of only a default association. In the function foo(), invoking this _Generic statement with any type results in selecting the default association. This generic selection is not useful and Polyspace reports a violation.

#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);
}

The _Generic statements get_type_id and get_type_id_with_default contain nondefault associations and Polyspace reports no violations.

Check Information

Group: Generic Selections
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a