Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Do not write any executable statement inside a switch loop statement before the first case statementlabel. The statements are never executed, as the compiler ignores statements present before the first case statement inside the switch block.

If a programmer declares variables and initializes them before the first case statement and try to use them inside any of the case statements, those variables will have scope inside the switch block, but will not be initialized and will consequently contain garbage values.

...

Noncompliant Code

...

Example

The example code mentioned below This noncompliant code example declares variables and write contains executable code statements before the first case statement in label within the switch loopstatement.

Code Block
bgColor#FFCCCC

int func(int expr) {
  switch(expr){
    int i = 4;
    f(i);
  case 0:
    i = 17;
  /* falls through into default code */
  default:	
    printf(“%d\n”, i);
  }
  return 0;
}

Implementation Details

On execution of above example on gcc version 4.1.2, the variable i is instantiated with automatic storage duration within the block, but is not initialized. Consequently, if the controlling expression has a non-zero value, the call to ((printf()}} will access an indeterminate value of i. Similarly, the call to function will also never get executed.

i

Output

0

17

nonzero

indeterminate

Compliant Solution

In this compliant solution, the statements before the first case statement are moved outside label occur before the switch blockstatement, improving the predictability and readability of the code.

Code Block
bgColor#ccccff
int func(int expr) {
	  int i = 4;    //* Move the code outside the switch block */
	  f(i);         //* Now the statements will get executed */

	  switch(expr) {
	    case 0:
	       i = 17;
	       /*falls through into default code */
	    default:	
		      printf(“%d\n”, i);
	  }
	  return 0;
}

Risk Assessment

Using test conditions or initializing variables inside the switch block before the first case statement, can result in unexpected behavior as the above code will not be executed.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC35-C

Medium

unlikely

medium

P2

L3

References

MISRA 04 chapter 6.14