Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jumping from one case to the default case in switch statement

Tags:

switch(ch){           case 'a':                  //do something, condition does not match so go to default case                  //don't break in here, and don't allow fall through to other cases.           case 'b':                  //..           case 'c':                  //..           case '_':                  //...           default:                  //                  break; } 

In a switch statement like above one I enter case 'a', I break only if the condition inside it occurs, otherwise I want to jump to default case. Is there any other way of doing this rather than labels or gotos?

like image 619
thetux4 Avatar asked Sep 20 '11 11:09

thetux4


People also ask

How do you call a default on a switch case?

The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.

What happens if you write default in switch case first?

The position of default doesn't matter, it is still executed if no match found. // The default block is placed above other cases. 5) The statements written above cases are never executed After the switch statement, the control transfers to the matching case, the statements written before case are not executed.

Can we skip default in switch case?

If there's no default statement, and no case match is found, none of the statements in the switch body get executed. There can be at most one default statement. The default statement doesn't have to come at the end.

Can we use two default in switch case?

A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses. A switch statement can only have one default clause.


2 Answers

goto For The Win

switch (ch) {     case 'a':         if (1) goto LINE96532;         break;     case 'b':         if (1) goto LINE96532;         break; LINE96532:     default:         //         break; } 
like image 117
pmg Avatar answered Oct 02 '22 15:10

pmg


Just reorder the cases so that that case is the last:

switch(ch){           case 'b':                  //..           case 'c':                  //..           case '_':                  //...           case 'a':                  //do something, condition does not match so go to default case                  if (condition)                      break;                  //don't break in here, and don't allow fall through to other cases.           default:                  //                  break; } 
like image 35
Diego Sevilla Avatar answered Oct 02 '22 14:10

Diego Sevilla