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.
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.
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.
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.
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.
Yes, there are differences. The cascaded if
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With