-2

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?

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
M.Ng
  • 65
  • 1
  • 4
  • 11

3 Answers3

2

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

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
1

If in switch case statement there is no break, all statements after the first matching case will be executed. S2 does not have any break statements, therefore, if ch = a, S2 will execute all statements below it, printing eh? eee eye ohh you.

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
MCG
  • 1,011
  • 1
  • 10
  • 21
0

Yes, there is a difference. In your first statement:

switch(ch) {
case 'a': printf("eh? "); break;

It will break here and only Print "eh? ". It won't execute second case 'e' part.

In your second statement:

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

If you select case 'a', it will execute 'a' and every case after that because there is no break in this statement. It will print "eh? eee eye ohh you ".

If you select case 'i', it will execute case 'i' and every case after that printing "eye ohh you ".

One more thing I would like to suggest, take 'A' and 'a' both cases. You can do that by:

switch(ch) {
  case 'a':case 'A': printf("eh? "); break;
  case 'e':case 'E': printf("eee "); break;
  case 'i':case 'I': printf("eye "); break;
  case 'o':case 'O': printf("ohh "); break;
  case 'u':case 'U': printf("you "); break;
  default: break;
}
nomeepk
  • 27
  • 6