M.Ng M.Ng - 1 year ago 92
C Question

C - Switch Statements - Difference in Output

I'm not really familiar with switch statements.

//S1
switch(ch) {
case 'a': printf("eh? "); break;
case 'e': printf("eee "); break;
case 'i': printf("eye "); break;
case 'o': printf("ohh "); break;
case 'u': printf("you "); break;
}

//S2
switch(ch) {
case 'a': printf("eh? ");
case 'e': printf("eee ");
case 'i': printf("eye ");
case 'o': printf("ohh ");
case 'u': printf("you ");
}


Is there a difference in outputs between these two chunks of code? And could you also please explain why?

Answer Source

Yes, there is a difference.

If the condition that matches the switch is in the topmost case statement, and you don't put a break (or return) in the end of it. It will fall through (execute all statements below it in the statemet).

For instance in the switch:

switch(ch) {
  case 'a': printf("eh? ");
  case 'e': printf("eee ");
  case 'i': printf("eye ");
  case 'o': printf("ohh ");
  case 'u': printf("you ");
}

if ch is equals to i, the printed output would be eye ohh you

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download