Is it possible to go to the default case while I'm in case 1/2/etc.?
switch(num) {
case 1:
if(foo) {
//do something
} else {
//go to default
}
...
...
...
default:
//do something
}
Even if you change num
value when you are in switch
the value for comparision is the value of variable before start of switch so if you've entered one of case
branches you cannot enter again into default
.
However you can do something like
boolean doDefault = false;
switch(num) {
case 1:
if(foo) {
...
}
else {
doDefault = true;
}
break;
}
if(doDefault) {
//do something
}
You could write the logic that is supposed to happen in the default
block in a function and call it when necessary:
void defAction(){
printf("Hello, World!\n");
}
int main() {
int num = 1, foo = 0;
switch(num) {
case 1:
if(foo) {
printf("Goodbye, World!\n");
} else {
defAction();
}
break;
default:
defAction();
}
return 0;
}
Remember, that if a case does not use break;
, all cases below it (including default
) are also called. This way, if you only break out of the switch if(foo)
, it will proceed to the default
. This is only really useful, if you want to jump to default
from no more than one case
, in which case you put that case
last, right before default
.
use with caution / see comments below
switch(num) {
case 2:
// do sth
break;
case 3:
// do sth
break;
case 4:
// do sth
break;
case 1:
if(foo) {
printf("Goodbye, World!\n");
break;
}
// ELSE don't break, use default
default:
defAction();
}
Not possible,doesn't make sense in real time application or in any use case,but if you want to go in default than you can do this by any of the following way-
case
. It's possible to make a method
switch(num) {
case 1:
if(foo) {
//do something
} else {
foo();
}
default:
foo();
}
不,您不能,但是您可以调用相同的方法或忽略中断。
您可以将它们放在默认值之前,并且不要在大小写结束时刹车,然后无论情况如何,它将在中断之前执行所有语句
You achieve this in a way below.
Suppose you need to go to the default case after case 1,2,8 only then you can write below code.
switch(Choice){
case 1 : //do something
case 2 : //do something
case 8 : //do something
default: //to do default operation
break;
case 3 :
case 4 :
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.