About MISRA-C 2012 Rule 16.7

Asked 2 years ago, Updated 2 years ago, 30 views

Rule 16.7 switch statement control expressions must not have a substantial Boolean type

However, is the use of constants in the control expression "substantial Boolean"?

Example:

#define NUM20
switch(NUM)
{
case10:
 break;
case20:
 break;
default:
 break
}

c

2022-09-30 15:00

1 Answers

In this case, the Boolean type is true/false similar binary.

switch(something){
case some_true:
   true_job();
   break;
default:
   false_job();
   break;
}

No, MISRA says this should be if.

If there are more than three values in the control expression, I believe that even if the value used in the switch is one value, it is not applicable.For example, if there are three or more command types for embedded communication specifications, such as "data acquisition", "data setting", and "reply", and a certain command (for now) only accepts "acquisition".

enum message_type {mt_query, mt_change, mt_reply};
/* Due to the communication telegram, this command only supports query for now */
switch(message_type()){
case mt_query:
    return build_query_result();
default:
    return build_negative_acknowledge();
}

It should be OK thatEven if MISRA warns against this code, the oira chooses to deviate because it may "extend the specification of the command in the future."

The example is hard to understand (if you really write such code, you reject it in source code reviews before MISRA) NUM is a variable, not a constant, value 10 is equivalent, value 20 is equivalent to false, and if it is passed to .


2022-09-30 15:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.