Why are long integers inappropriate for switch expressions?

Why are long integers used in switch expressions (C99) flagged as a defect for being an inappropriate data type in Polyspace Bug Finder?
Matlab documentation only allows char, int, short or enum. Considering int can be either a 64 or 32 bit integer dependent on platform, it seems that a long, an explicit 32 bit integer, should be allowed.
Link to Matlab documentation of defect:
Example:
unsigned long x = 1u;
switch(x) // Defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
unsigned int y = 1u;
switch(y) // No defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
Thanks,
Tommy

6 Comments

Good question. BTW, is "short" even belong to one of the data types?
Fangjun,
Since you commented, I editted my question for accuracy. "Char, short, int and enum" are explicitly allowed and "boolean types, bit fields, or long" are explicitly prohibited per the documentation at https://www.mathworks.com/help/bugfinder/ref/possiblyinappropriatedatatypeforswitchexpression.html
Thanks,
Tommy
Okay, for that, I think the document explains it and it is reasonable.
"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." int type allows 65536 cases. That is more than enough for the code flow. If it needs more than that, it is suggested to use a different approach.
I thought your previously asked why "int" is not a defect but "unsigned int" caused a defect.
Short integers: short
This doesn’t get used often, but it’s good to know that it exists. Like int, it can store -32768 to 32767. Unlike int, however, this is the extent of its ability. Anywhere you can use short, you can use int.
I mixed up data types in C and MATLAB.
I agree that managing more than 2^16 explicit cases likely requires a different approach. However, if the cases being checked are more finite (ie. only checking for 10 exact values out of 2^32), the "default" case handles the excess well. Couldn't this warning be more direct by checking the number of cases in a switch statement then?
Thanks,
Tommy
That seems like a reasonable enhancement request for Polyspace Bug Finder. I recommend you submit to Technical Support so they can record it in the enhancement database.

Sign in to comment.

Answers (0)

Products

Release

R2024a

Asked:

on 10 Jul 2024

Commented:

on 10 Jul 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!