Main Content

MISRA C:2023 Rule 23.1

A generic selection should only be expanded from a macro

Since R2024a

Description

Rule Definition

A generic selection should only be expanded from a macro.

Rationale

Generic selections allow you to query the type of its argument and then select different actions for different types. By selecting actions depending on the type of the argument, your code can accommodate generic functions. If you use generic selection directly in your code, then the type of its operand is already known and the generic selection is no longer useful.

The best practice is to implement generic selection in a function-like macro and perform selection based on the type of its argument.

Polyspace Implementation

This rule checker reports a violation if either of these conditions are met:

  • A generic selection is not expanded from macro.

  • The selector of a generic selection is not an argument of the expanded macro.

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 this example, the generic selection statement _Generic(x, int:1, float:2) is not expanded from a macro and used directly. When authoring this generic selection, the type of x is already known. This generic selection is not useful. The rule checker reports a violation.

int x = 0;
void f() {
    
    int y = _Generic( x    /*Noncompliant*/
                , int : 1
                , float : 2 );
}


extern void handle_int(int x);
extern void handle_float(float x);
extern void handle_any(char x);
#define arith(X) ( _Generic( (X) /* Compliant*/\
                    , int : handle_int \
                    , float : handle_float \
                    , default : handle_any \
                    ) (X) )
/* Non-compliant */
#define maybe_inc(Y) ( _Generic( x /* Noncompliant*/\
                    , int : 1 \
                    , default : 0 ) + (Y) )

void foo() {
    unsigned char c = 0;
    arith(c);         
    maybe_inc(c);
}

In the generic selection macro maybe_inc, the type selection depends on the type of x, which is not an argument of maybe_inc. The rule checker reports a violation.

Check Information

Group: Generic Selections
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a