Why are long integers inappropriate for switch expressions?
Show older comments
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
Fangjun Jiang
on 10 Jul 2024
Good question. BTW, is "short" even belong to one of the data types?
Tommy
on 10 Jul 2024
Fangjun Jiang
on 10 Jul 2024
Edited: Fangjun Jiang
on 10 Jul 2024
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.
Fangjun Jiang
on 10 Jul 2024
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.
Tommy
on 10 Jul 2024
Steven Lord
on 10 Jul 2024
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.
Answers (0)
Categories
Find more on Configure Coding Rule Checks and Code Metrics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!