I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.
- for A, I want to do statement_1 and statement_3.
- for B, I want to do statement_2 and statement_3.
- for C, I want to do nothing
if I use if-else statement, it will look like the following:
if ( not C){
do statement_3
if B
do statement 2
else if A
do statement 1
}
If I want to use switch statement to do the same thing, I have some trouble.
switch (variable){
case A: do statement_1
case B: do statement_2
// how to do statement 3 here?
}
I am trying to avoid the duplicated codes. So I am thinking that how to make the codes as simple as I can.
UPDATE 1:
to make my codes/question more clear, I just want to make my codes as simple/clear as I can, that is why I want to use switch statement instead of if-else. Also, I heard that switch-statement is usually faster than if-else. (I am not 100% sure though).
I want to use switch-case because Case A, B, C are enum type. they are not variable. Sorry about the confusion.
each statements are more than 10 lines of codes. That is why I do not want to do the followings:
switch (enum variable) { case A: statement1 statement3 break; case B: statement2 statement3 break;}
if? If a switch is not the right tool, don't use it. Most of the time, it's not the right tool.