Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if inside a switch case, to restrict cases

Tags:

c++

c

thanks for the answers.

I would like to know if is it possible to restrict some cases of a swtich-case statement using conditional expressions. Like the code the follows.

switch(a)
{
    case 1:
    {
        do_1();
        break;
    }
    case 2:
    {
        do_2();
        break;
    }

    if(condition)
    {
        case 3:
        {
            do_3();
            break;
        }

        break;
    }
}

Edited, sorry guys, I got the wrong condition, it's not related at all with the switched variable. Just another condition, external one. I just want to know if I can restrict the cases with an external conditions, otherwise, that cases inside the IF won't be analyzed if the condition is not satisfied.
Do I need the second break inside the if?

like image 431
liuroot Avatar asked Nov 30 '22 15:11

liuroot


1 Answers

The short answer is no. You'd have to reverse the order:

case 3: 
    if (condition) 
        do_3();
    break;
like image 75
Jerry Coffin Avatar answered Dec 05 '22 01:12

Jerry Coffin