The only real difference is that a switch statement tests the same variable against a series of possible values whereas a nested if has no limitation as to what condition(s) are tested. Other than that, the two structures should compile and execute almost identically in terms of size and speed.
The functionality of the two can be the same, however, when dealing with case scenarios, you should use a switch statement in order to preserve the readability of the code.
A switch statement is usually much easier to understand than a load of nested if statements.
Do you mean if-else if-else statements as oppsed to nested ifs?
The main difference (other than readability) is that with an if-else if, you don't have to test the same value on each comparison. For example, you can do this with an if-else if (not that it would make much sense, it would be "iffy" coding, IMO, but it can be done)
Answers & Comments
Verified answer
The only real difference is that a switch statement tests the same variable against a series of possible values whereas a nested if has no limitation as to what condition(s) are tested. Other than that, the two structures should compile and execute almost identically in terms of size and speed.
The functionality of the two can be the same, however, when dealing with case scenarios, you should use a switch statement in order to preserve the readability of the code.
A switch statement is usually much easier to understand than a load of nested if statements.
Do you mean if-else if-else statements as oppsed to nested ifs?
The main difference (other than readability) is that with an if-else if, you don't have to test the same value on each comparison. For example, you can do this with an if-else if (not that it would make much sense, it would be "iffy" coding, IMO, but it can be done)
if (color == brown)
{
do something
}
else if (color == red && size == small)
{
do something else
}
else if (height == tall)
{
do something else
}
else
{
do last thing
}