Re: if and case statements
ragabs,
IF-ELSE statement differs from SWITCH-CASE statement.
1. SWITCH works only with discrete or single expresssion.
Unlike IF, no equalities are allowed.
SWITCH sets the program counter or jumps the program directly to the program segment when expression in SWITCH matches the condition in CASE.
For example,
Code:
switch( Grade )
{
case 'A' : printf( "Excellent" );
case 'B' : printf( "Good" );
case 'C' : printf( "OK" );
case 'D' : printf( "Mmmmm...." );
case 'F' : printf( "You must do better than this" );
default : printf( "What is your grade anyway?" );
}
2. IF works can work with many expressions, from Boolean TRUE and FALSE, range of integers to bitwise comparison. This is because IF works with TRUE or FALSE when expressions are compared with a reference or conditions already defined by you.
For example,
Code:
if ( var_a >= var b) // notice that equality is used.
if ( function1(var_a) == var_b ) // notice IF statement allows implicit function.
if ( var_a ) // notice IF statement tests the TRUE-FALSE of var_a.
IF statement allows qualities. This is very useful when you are working with a range of values. SWITCH will become helpless to work with equalities.
Regarding speed, IF and SWITCH works the same because they need to compare expressions with conditions.
For example:
Code:
switch( Grade )
{
case 'A' : printf( "Excellent" );
case 'B' : printf( "Good" );
case 'C' : printf( "OK" );
case 'D' : printf( "Mmmmm...." );
case 'F' : printf( "You must do better than this" );
default : printf( "What is your grade anyway?" );
}
Code:
if ( Grade == 'A' ) printf( "Excellent" );
elseif ( Grade == 'B' ) printf( "Good" );
elseif ( Grade == 'C' ) printf( "OK" );
elseif ( Grade == 'D' ) printf( "Mmmmm...." );
elseif ( Grade == 'F' ) printf( "You must do better than this" );
else printf( "What is your grade anyway?" );
In the above example, both SWITCH and IF works the same way and the same speed. We must remember the set of conditions from A to F are already defined. Both and SWITCH and IF have to compare the expression with the condition one by one until they match.
Ultimately, C Program will eventually be compiled into Assembly Progam specific to the RISC processor.
SWITCH is like BEQ (Branch Equal) and IF is like BHI (Branch Higher), although BEQ can also be used for IF.
If you know the conditions you are working with, use the right statemenet, IF or SWITCH and define the appropriate expressions to work with your conditions.