Versions Compared

Key

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

Do not write any executable statement inside a switch loop before the first case statement. The statements will are never get executed, as the compiler will ignore the ignores statements present before the first case statement inside the switch block. The compiler will compile the above statements, but while generating assembly for the switch loop, those statements will be ignored.

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 their value will not be taken initialized and will consequently contain garbage . Any unexpected result can follow because of the above behavior.values.

Non Compliant Code:

In the example mentioned below, the variable i will be is instantiated with automatic storage duration within the block, but it’s never is not initialized. ThusConsequently, if the controlling expression has a non-zero value, the cause call to ((printf()}} will access an indeterminate value of i. Similarly, the call to function will also never get executed.

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;
}

Compliant Solution

In the this compliant solution, by moving the statements before the first case statement are moved outside the switch block, improving the execution can be ensured and result in an expected behaviorpredictability 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;
}

...

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

...