Main Content

Possibly inappropriate data type for switch expression

switch expression has a data type other than char, short, int or enum

Since R2020a

Description

This defect occurs when a switch expression has a data type other than char, short, int or enum.

The checker flags other integer data types such as boolean types, bit fields, or long.

Risk

It is preferred to use char, short, int or enum in switch expressions instead of:

  • Boolean types, because a switch expression with a boolean type can be replaced with an if condition that evaluates the same expression. A switch expression is too heavy for a simple control flow based on a boolean condition.

  • Bit field types, because bit field types imply memory restrictions. If you just want to specify a variable with a finite number of values, enumerations are preferred since they enable a more readable code.

  • Types with size greater than int because a switch expression that requires a type with size greater than int implies too many case labels and can be possibly redesigned.

Non-integer types are not supported in switch expressions.

Fix

Use variables of char, short, int or enum data types in switch expressions.

Examples

expand all

#ifndef __cplusplus
#include <stdbool.h>
#endif

void func(bool s) {
    switch(s) {
        case 0: //Perform some operation
        break;
        case 1: //Perform another operation
        break;
    }
}

In this C++ example, the checker flags the use of a bool variable in a switch expression.

Correction – Use if Condition Instead of switch

If the switch expression indeed requires two values, use an if statement instead.

#ifndef __cplusplus
#include <stdbool.h>
#endif


void func(bool s) {
    if(s) {
        //Perform some operation
        }
    else {
        //Perform another operation
        }
}
Correction – Use Different Data Type

If you anticipate adding more labels to the switch expression later, use a data type that can accommodate larger values.

void func(char s) {
    switch(s) {
        case 0: //Perform some operation
        break;
        case 1: //Perform another operation
        break;
        default: //Default behavior
    }
}

Result Information

Group: Good practice
Language: C | C++
Default: Off
Command-Line Syntax: INAPPROPRIATE_TYPE_IN_SWITCH
Impact: Low

Version History

Introduced in R2020a