Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be the approach to avoid duplicate code in below pseudo c code snippet?

Tags:

c

algorithm

if(var == something) {
    A();
    B();
} else if(var == something_else) {
    A();
    B();
    C();
} else {
    assert(false);
}

How can i avoid duplicate code of calling A() and B() in both if cases. Should i use switch case like,

switch(var) {
case something:
case something_else:
    A();
    B();
    break;
}
if (var == something_else)
   C():

What is the better solution? Is there any performance penalty in switch vs if else?

like image 586
Jagdish Avatar asked Dec 19 '22 23:12

Jagdish


2 Answers

if (var == something || var == something_else) {
    A();
    B();
}

if (var == something_else) {
    C();
}

If you also need the else, you can do this:

if (var == something || var == something_else) {
    A();
    B();

    if (var == something_else) {
        C();
    }
} else {
    assert(false);
}

In regards to your question,

Is there any performance penalty in switch vs if else?

Please read the answers to this question:

Is 'switch' faster than 'if'?

In short, normally there wouldn't be any noticeable difference. So you should write your code with the readability in mind. Between if/else and switch, just choose whatever is more natural.

like image 194
Dmytro Shevchenko Avatar answered Dec 22 '22 01:12

Dmytro Shevchenko


As calling order doesn't matter, try this:

switch(var) {    
    case something_else:
        C();
    case something:
        A();
        B();
    break;
    default:
        assert(false);
    break;
}
like image 28
rakeb.mazharul Avatar answered Dec 22 '22 01:12

rakeb.mazharul