English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Are there situations when we will not be able to use the Switch structure instead of the if-else structure?

2007-03-22 17:45:01 · 2 answers · asked by TheOne 1 in Computers & Internet Programming & Design

2 answers

The switch structure is faster than if/else from a raw cpu-cycles standpoint. So switch should be used whenever possible, for pure performance reasons. It is the best option when you need to create logic branches based on a simple enumerated value. if/else is appropriate when you need to do comparison logic.

As an example, you would use switch if you have a limited number of logic branches, based on a value being within a known literal range. For example, if the variable will be 1, 2, 3, or something else, it is appropriate to use switch.

However, if your logic branch depends on comparison logic, such as whether the value of a is equal to the value of b, you would use if/else logic. You cannot substitute switch for if/else in a comparison logic situation.

2007-03-22 17:57:26 · answer #1 · answered by Rex M 6 · 0 1

usually the swicth structure is used instead of the if-else structure if you need only to directly compare values to certain other values. If you're using nested conditions in your if-else then you can't substitute it for a swicth class.
To better illustrate, consider the following:

possibility 1:

int a = 1;

if(a == 0)
{
//do something
}
else if(a == 1)
{
//do something else
}
.
.
.
else
{
//default action
}

(in this situation you can substitute your if-else for a swicth, which would then look like this)

switch(a)
{
case 0:
//do something
break;
case 1:
//do something else
break;
.
.
.
default:
default action
//break;
}


possibility 2:
however, if you have something like this...

int a = 1;

if( a > 0 && a < 5)
{
//do something
}
else if( a > 5 && a < 6)
{
//do something else
}
.
.
.
else
{
//default action
}

...you won't be able to substitute this particular if-else for a swicth. As i've said before, the a switch can only take into account single conditional comparisons to a specific value. In this situation, you have a nested condition and the conditions test relativity of the values (greater or lesser).
(--bow-- ;) )

2007-03-23 01:10:53 · answer #2 · answered by czimon 2 · 0 1

fedest.com, questions and answers