Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference in C and C++ between using if, else if, else if, ... and using switch () { case A: ... case B: ... }?

Tags:

c

I am interested if there is any difference from the C or C++ compiler perspective whether I use:

if (value == a) {
    ...
}
else if (value == b) { 
    ...
}
else if (value == c) { 
    ...
}

versus

switch (value) {
    case a:
        ...
        break;
    case b:
        ...
        break;
    case c:
        ...
        break;
}

It feels to me that there is no difference, just syntactic. Does anyone know more about it?

Thanks, Boda Cydo.

like image 804
bodacydo Avatar asked Jul 29 '10 17:07

bodacydo


People also ask

What is the difference between if-else and ELSE IF in C?

The difference between else and else if is that else doesn't need a condition as it is the default for everything where as else if is still an if so it needs a condition.

What is the difference between an if statement an if-else statement and an if-else IF statement?

Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

What is the difference between if-else and if-else if control structure?

IF-ELES: if the condition is true, then the block of code inside the IF statement is executed; otherwise, the block of code inside the ELSE is executed. IF-ELSE-IF: if the condition is true, then the block of code inside the IF statement is executed. After that, the ELSE-IF block is checked.

What is the difference between if condition and if-else condition?

With the if statement, a program will execute the true code block or do nothing. With the if/else statement, the program will execute either the true code block or the false code block so something is always executed with an if/else statement.


1 Answers

Yes, there are differences. The cascaded ifs guarantee evaluation of the conditions in order. The switch guarantees only a single evaluation of whatever's used as the switch parameter. Depending on the compiler, the switch will often take (nearly) constant time regardless of the selected branch, whereas the if cascade pretty much guarantees that the first leg is the fastest, the second second fastest, and so on down to the last being slowest.

like image 189
Jerry Coffin Avatar answered Nov 14 '22 23:11

Jerry Coffin