Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does switch statement work?

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.

like image 986
Bazooka Avatar asked Feb 23 '12 07:02

Bazooka


People also ask

How does the switch statement work in C?

The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. The break statement breaks out of the switch block and stops the execution.

How does a switch statement work in Java?

The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.

What is switch statement explain with example?

Switch Case Example in CA switch construct is used to compare the value stored in variable num and execute the block of statements associated with the matched case. In this program, since the value stored in variable num is eight, a switch will execute the case whose case-label is 8.

What do switch statements do?

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.


3 Answers

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.

like image 85
Alok Save Avatar answered Oct 13 '22 00:10

Alok Save


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.

like image 32
Jerry Coffin Avatar answered Oct 13 '22 00:10

Jerry Coffin


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;
}
like image 44
Jeegar Patel Avatar answered Oct 12 '22 23:10

Jeegar Patel