You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Next »

Do not write any executable statement inside a switch loop before the first case statement. The statements will never get executed, as the compiler will ignore the 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 be taken garbage. Any unexpected result can follow because of the above behavior.

Non Compliant Code:

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

int func ( int expr )
{
switch (expr)

Unknown macro: { int i = 4; f(i); case 0}

return 0;
}

Compliant Solution

In the compliant solution, by moving the statements before the first case statement outside the switch block, the execution can be ensured and result in an expected behavior.

  • No labels