answersLogoWhite

0


Best Answer

1.Switch statement looks a lot more tidy and easy to read and understand.

2.Here multiple statements need not to be enclosed within a pair of braces.

3.Switch statement executes faster than if_else because the switch statement checks the condition first and then jumps to the suitable case statement.

User Avatar

Wiki User

12y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

7y ago

When code must branch we can either use an if statement or a switch statement. For a simple binary branch an if statement suffices, however for more complex branching a switch statement is usually preferred. The advantages of a switch statement can be summarised as follows:

1. Cleaner code

Switch statements are structured, resulting in cleaner code which is easier to both read and maintain, particularly with dense-case structures.

2. Performance

For dense cases, the compiler generates an efficient jump table from a single evaluation. For sparse case tables the compiler will either perform a binary search or will generate the equivalent if statement (what we refer to as a thinly-disguised switch statement). Thus the worst case performance of a switch statement is equivalent to that of an if statement, but is typically faster.

3. Precedence

The order of control expression in an if statement is important, typically capturing the most common case and working down to the least common. With a switch statement the order is less important, making it easier to add new cases without having to consider the precedence. However, see 5 below.

4. Default Case

The default case (if required) can be placed anywhere in a switch statement. With an if statement it must be placed last even if it is the most common case, which is inefficient.

5. Common Code

By omitting the break statement before the next case, execution will fall-through to the next case (the label is simply ignored), thus allowing two or more cases to be grouped together in order to execute code that is common to those cases. With an if statement, common code either has to be placed in a separate function (preferably one that can be inline expanded), duplicated in full (creating maintenance problems), or made accessible through a goto statement. A switch statement is effectively a procedural jump (using goto), so it makes no sense to avoid a procedural jump using a procedural jump.

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

There are no disadvantages as such since they are both designed for completely different purposes. An if statement can only evaluate true or false so if you wanted to emulate a switch statement using a series of if statements then you'd end up evaluating the same expression in every if statement until you encountered one that was true. Consider the following example:

void f (int i)

{

if (i==0) {/*...*/}

else if (i==1) {/*...*/}

else if (i==2) {/*...*/}

else if (i==3) {/*...*/}

else {/*...*/}

}

If you were to call f(3), you'd end up evaluating the following sequence of expressions:

3==0 (false)

3==1 (false)

3==2 (false)

3==3 (true)

That's 4 separate operations to reach the one piece of code you actually wanted to execute.

Now consider the switch version:

void g (int i)

{

switch (i)

{

case 0: {/*...*/}; break;

case 1: {/*...*/}; break;

case 2: {/*...*/}; break;

case 3: {/*...*/}; break;

default: {/*...*/};

}

}

If you call g(3), you perform one evaluation (returning the value 3) and automatically jump to case label 3. That is clearly more efficient than a series of if statements.

Conversely, if you had the following if statement:

void f (int i)

{

if (i&1) {/*...*/};

else {/*...*/}

}

It makes no sense to use a switch since there is only one evaluation to consider:

void g (int i)

{

switch (i&1)

{

case true: {/*...*/}; break;

default: {/*...*/}

}

}

The switch is really no less efficient than the if statement, but the if statement expresses the idea of a boolean expression more directly. The switch simply makes code slightly harder to read by obfuscating the logic.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Advantages of switch - case over if else?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

If then else statements and case statements essentially perform the same function when would you use one over the other?

I would recommend an If - then - else statement over a switch statement because:1. It is simpler/easier2. You do not get unexpected output because of missing break statementsA missed break statement in one of the conditions in a switch case statement means that all the conditions that come after the success condition are executed. In case of if else this is not the case and hence it is much safer for novice programmers.> essentially perform the same functionNo, they don't. Here is an example to prove this:if (sin (alpha) > cos (alpha)) {...} else if (alpha / M_PI * 180 > 180) {...} else {...}


What is the role of switch statement in c plus plus?

Switch is an alternative to using a long sequence of if...else if... statements where each conditional expression is essentially the same, evaluating to the same data type but with different values. For instance: if(x==1) statement_1; else if(x==2) statement_2; else if(x==3) statement_3; else statement_4; The above can also be written: switch(x) { case(1): statement_1; break; case(2): statement_2; break; case(3): statement_3; break; default: statement_4; } Most would regard the second version as more readable as there's only one conditional expression to evaluate.


Use of nested switch case?

KVM switches are available via hardware and now today over IP software is also available...many switch, keyboard and video combinations are possible.


Difference between if and switch in C?

The switch statement evaluates an expression, which must have an integral result. Based on that result, a branch is taken to one of the case statements, or to the default statement if present and none of the case statements match.Note that the case statement represents a "goto" type of operation. If it is intended that each case execute without executing the following case statement(s), then each case must include a break statement.The if-else statement evaluates an expression, which must have a logical result. If the result is true, the first target statement executes - if false, the second target statement executes.


What is the syntax and purpose of the switch statement in c plus plus?

The purpose of a switch statement is to execute one of several sections of code, depending on the value of an integral expression. The syntax of a switch statement can be stated as follows: switch(expression) { case(constant_expression_1): statement case(constant_expression_2): statement //.. case(constant_expression_n): statement [default: statement] } The ellipses around the constant expressions are optional and may be omitted. The switch statement body consists of one or more case labels and an optional default label (the case labels are also optional, but a switch statement would be meaningless without them). The default statement, if present, need not be the final label in a switch statement. Case and default labels may not appear outside of a switch statement, as they are not treated the same as goto labels. The constant_expression in each case label is converted to the type of the switch expression and is compared with the switch expression for equality. Control is immediately passed to the labelled statement whose constant_expression matches the value of the switch expression. Once a label gains control, execution proceeds from that point on and is not impeded by any subsequent case or default labels. However, a break statement may be used to interrupt execution at any time, which will transfer control to the statement immediately following the switch statement body. You may also use a return statement to return control to the calling function, or a goto statement. However, note that while a goto label is not the same as a case label, you may use goto labels inside a switch statement if required. Here's an example demonstrating how code flows through a switch statement: int x; switch(x=rand()%10) // x is a random number in the range 0 to 9. { case(0): x=42; break; case(1): case(2): x=33; break; case(3): x=100; default: x=0; } If x were 0, then execution passes to case(0) where the value 42 is assigned to x and the switch exits. If x were 1 or 2, then 33 is assigned to x and the switch exits. If x were 3, 100 is assigned to x. In all other cases, 0 is assigned to x. You will note that when the switch statement ends, x can only ever be 42, 33 or 0. Why not 100? Look again and you will see that case(3) has no break statement (just as case(1) has no break statement). So although 100 is assigned to x in case(3), the default case immediately assigns 0 to x. This is not a particularly useful switch statement, but it serves to demonstrate how code flows through a switch statement, and how forgetting to put a break statement at the end of a case can cause unexpected errors to creep into your code. While you could emulate the same results using a series of if, else if and else statements, the benefit of a switch statement is that it will generally simplify the complexity of your code, because there is only one expression to evaluate, rather than a series of boolean expressions. Your compiler will generate machine code just as if you'd used a series of if statements, but the switch statement gives a greater sense of structure to the statement, and gives a greater degree of control over which section(s) of code will execute for any given evaluation. And just as ifs can be nested within other ifs, switch statements can be nested within other switch statements. Note that all code in a switch statement must be reachable (that is, not bypassed by all execution paths). For instance the following contains both unreachable and undefined code: switch(x) { x=42; //unreachable case(100): int y=42; break; default: x=y; // y is undefined } The line x=42 cannot be reached because execution must either pass to either the case(100) or the default label. Similarly, the x=y line is invalid because y is defined within the case(100) label, which is not reachable from within the default label due to the break statement.

Related questions

If then else statements and case statements essentially perform the same function when would you use one over the other?

I would recommend an If - then - else statement over a switch statement because:1. It is simpler/easier2. You do not get unexpected output because of missing break statementsA missed break statement in one of the conditions in a switch case statement means that all the conditions that come after the success condition are executed. In case of if else this is not the case and hence it is much safer for novice programmers.> essentially perform the same functionNo, they don't. Here is an example to prove this:if (sin (alpha) > cos (alpha)) {...} else if (alpha / M_PI * 180 > 180) {...} else {...}


What is advantage of push button over toggle switch?

One of the main advantages of a push button over a toggle switch is there is less room for accidental engagements. A toggle switch can easily be turned on or off by accident and a push button has to be intentionally touched to turn it on or off.


When can the server in volleyball enter the court after service?

after the play is over and your coach asks for you and someone else to switch


What is the advantage of switch statement over else -if construct?

Switch statements typically provide cleaner code that is easier to both read and maintain. Switch statements have a worst case performance equivalent to that of a chain of if else statements. However, a dense case list can often be converted to an efficient jump table or even a binary search table, which improves efficiency. Where a switch can convert to a jump table or a binary search table, the order of the cases does not matter. This makes it easier to add new cases wherever we like. With a chain of if else statements we typically cater for the most common case first to improve efficiency, but the default case must always come last, even if it is the most common case. With a switch we can place the default case anywhere. With a switch statement, execution passes through case labels until a break is encountered, thus allowing us to execute code that is common to more than one case. With if else statements we must duplicate that common code or else place the common code in a function that can be invoked from each case.


What tasks does the inertia switch perform in cars?

my husband is a mechanic. he said it is a rollover switch. it shuts off the fuel in case the car rolls over.


What are the advantages of using a 4 wheel suitcase over a two wheel suitcase?

The advantages of using a 4 wheel suitcase over a two wheel suitcase include the ability to be able to drag the case over a long, flat distance without overt strain to the wrist because of the angle at which a two wheeled case must be held to move it.


Your 92 camaro wont start replaced starter and ignition switch has power but wont turn over what else could it be?

Check the 92 Camaro neutral safety switch next. If the switch is faulty then the starter will not get power to start the engine.


What are the advantages and disadvantages RAM?

A DVD-RAM is longlasting and can be rewritten over a lot of times. Also it comes i a case so that it does not get damaged.


What are the advantages and disadvantages of Ram?

A DVD-RAM is longlasting and can be rewritten over a lot of times. Also it comes i a case so that it does not get damaged.


What the advantages and disadvantages of bridges and switches?

well an advantage for the bridge is u get over water instead of running into a river. and an advantage for a switch is u can turn stuff on and off.


What is the role of switch statement in c plus plus?

Switch is an alternative to using a long sequence of if...else if... statements where each conditional expression is essentially the same, evaluating to the same data type but with different values. For instance: if(x==1) statement_1; else if(x==2) statement_2; else if(x==3) statement_3; else statement_4; The above can also be written: switch(x) { case(1): statement_1; break; case(2): statement_2; break; case(3): statement_3; break; default: statement_4; } Most would regard the second version as more readable as there's only one conditional expression to evaluate.


Use of nested switch case?

KVM switches are available via hardware and now today over IP software is also available...many switch, keyboard and video combinations are possible.