18

How are statements that come before any case labelled statement in a switch-case block treated. Please explain the behavior of the following programs

prog1:

#include<stdio.h>
int main()
{
  switch(1)
  {   
    int i=0; 
    case 1:printf("%d",i);         
  }
getchar();
return 0;
}

Output: garbage value.

prog2:

#include<stdio.h>
int main()
{
  switch(1)
  {  
    printf("Inside Switch");  
    case 1:printf("Case 1\n");      
  }
  printf("Outside Switch");
  getchar();
  return 0;
}

Output:

Case 1

Outside Switch.

The statements before a case labelled statement seem unreachable according to program 2 but then why don't i get an error for an undeclared variable i in the first program (only a warning).

Would be really helpful if someone could explain in detail that how the switch statement is treated internally.

Bazooka
  • 1,428
  • 4
  • 15
  • 24
  • 1
    Is this homework? It sounds like homework. If so, add the `homework` tag and show your own work so far. – T.J. Crowder Feb 23 '12 at 07:47
  • 2
    @T.J.Crowder This is not homework.I came across this while taking the C quiz on gild and i am curious to know. – Bazooka Feb 23 '12 at 07:50
  • A `switch` statement is basically syntactic sugar for a jump table with `goto`s. – David Schwartz Feb 23 '12 at 07:52
  • Have you tried compiling the use of an undeclared variable outside a switch scope with the same compiler? What does it output? Maybe it depends on the warning/error settings of your compiler? And here: http://www.cprogramming.com/tutorial/lesson5.html – The Nail Feb 23 '12 at 07:52
  • @TheNail I did try that. But it gave an error message. – Bazooka Feb 23 '12 at 07:55
  • Ah so the warning is not for an undeclared variable, just for being uninitialized. I see. – The Nail Feb 23 '12 at 07:57

3 Answers3

9

This is best explained by quotations from the c standard. I am quoting the relevant parts from the standard which apply to your question here.

6.8.4.2 The switch statement

Para 4:

A switch statement causes control to jump to, into, or past the statement that is the switch body, depending on the value of a controlling expression, and on the presence of a default label and the values of any case labels on or in the switch body......

Para 2:

If a switch statement has an associated case or default label within the scope of an identifier with a variably modified type, the entire switch statement shall be within the scope of that identifier.154)

FootNote:

154) That is, the declaration either precedes the switch statement, or it follows the last case or default label associated with the switch that is in the block containing the declaration.

Para 7:
EXAMPLE In the artificial program fragment

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

the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.


The above mentioned applies to both of the code examples in the Question.
Example 1, i has an Indeterminate value since it was never initialized & hence prints garbage, While in
Example 2, printf call is not reached because the control jumps to the matching case label.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    thanks for this and others you have answered for me. Much appreciated. – Bazooka Feb 23 '12 at 08:32
  • +1. I have also a small writeup on how they get implemented by compiler if you are interested, see [here](http://lazarenko.me/2013/01/13/switch-statement-machine-code/). –  Jan 13 '13 at 20:44
5

Basically, a switch acts like a goto to the appropriate label -- intervening statements aren't executed. Variable definitions (which actually happen at compile time) do happen, but if they contain initialization, that's skipped too.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

Never write statements in switch which are not part of any case or default because they won't be executed.

NOTE: declaration can be written there but not statement (int i; is declaration but int i = 10; is declaration + assignment = statement so assignment will not be perform there..!)

switch(a)
{
printf("This will never print"); // this will never executed
case 1:
        printf(" 1");
break;
 
default :
break;
}
DonCarleone
  • 544
  • 11
  • 20
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222