Últimos assuntos
Quem está conectado?
Há 3 usuários online :: 0 registrados, 0 invisíveis e 3 visitantes Nenhum
[ Ver toda a lista ]
O recorde de usuários online foi de 73 em Qui 1 Fev 2024 - 6:28
Procurar
When Should You Use 'switch' Instead of 'if-else' in C...
Fórum de Electrónica - projectos, cursos, tutoriais, compra e venda, etc. em electrónica :: Electronic in general - Threads in English
Página 1 de 1
When Should You Use 'switch' Instead of 'if-else' in C...
You can think of switch statements as if they are multiple sets of if statements.
The other advantage is that the tested expression(immediately following the switch statement) is only performed once. A good optimising compiler may recognise the expression code '(PORTA & 0x30)>>4' in the if-else statements but then again it may not. By using the switch statement the compiler does not need to put effort into optimisation so you know you will get the fastest possible code.
Note: You have to test the output code for maximum optimization i.e. force the compiler to use a specific data type if necessary (by casting) as data types can have unexpected results on code speed.
Warning the ONLY crucial thing you must remember about switch statements is
"break;"
This is the major difference between "if - else" and switch
Consider this code
still the same as before but not for case 2. The code will now "fall through" to case 3 so when case 2 fires the delay will be 40+100 ms.
It looks useless but it is a convenient way of coding multiple case(es) to do the same job.
For instance if you wanted to do the same operation for different 'case values' you allow "fall through" to occur.
Of course this is a trivial example but in the real world the advantage is that you don't have to write un-maintanable code.
e.g.
The 'if - else' construct is useful for small sections of decision code but if you find yourself creating a huge list of 'if else if else' statements then use a switch instead but beware of the 'break;' statement.
Note: You can super reduce an if statement using the conditional construct (expr ? true : false) see the C course for details of its use.
Switch statements are used extensively to create and control state machines as they conveniently separate state machine operation or "the state transition code" from the "state action code". State machines are used within windows programming, VHDL (diff. syntax but essentially the same idea) and embedded programming.
All use a switch type construct for clarity of programming intention.
Font: www.best-microcontroller-projects.com
- Código:
switch ( (PORTA & 0x30)>>4 ) {
case 1 : delay_ms(500); break;
case 2 : delay_ms(100); break;
case 3 : delay_ms(40); break;
default: delay_ms(200);
}
- Código:
if ( (PORTA & 0x30)>>4==1 ) delay_ms(500);
else if ( (PORTA & 0x30)>>4==2 ) delay_ms(100);
else if ( (PORTA & 0x30)>>4==3 ) delay_ms(40);
else delay_ms(200);
The other advantage is that the tested expression(immediately following the switch statement) is only performed once. A good optimising compiler may recognise the expression code '(PORTA & 0x30)>>4' in the if-else statements but then again it may not. By using the switch statement the compiler does not need to put effort into optimisation so you know you will get the fastest possible code.
Note: You have to test the output code for maximum optimization i.e. force the compiler to use a specific data type if necessary (by casting) as data types can have unexpected results on code speed.
Warning the ONLY crucial thing you must remember about switch statements is
"break;"
This is the major difference between "if - else" and switch
Consider this code
- Código:
switch ( (PORTA & 0x30)>>4 ) {
case 1 : delay_ms(500); break;
case 2 : delay_ms(100);
case 3 : delay_ms(40); break;
default: delay_ms(200);
}
still the same as before but not for case 2. The code will now "fall through" to case 3 so when case 2 fires the delay will be 40+100 ms.
It looks useless but it is a convenient way of coding multiple case(es) to do the same job.
For instance if you wanted to do the same operation for different 'case values' you allow "fall through" to occur.
- Código:
switch (key) {
case 'a' :
case '1' : print_scr("changing mode"); break;
case '2' : print_scr("2"); break;
case '3' : print_scr("3"); break;
default: delay_ms(200);
}
Of course this is a trivial example but in the real world the advantage is that you don't have to write un-maintanable code.
e.g.
- Código:
switch (key) {
case 'a' : print_scr("changing mode");
turn_fan_on();
apply_brakes();
engine_off();
break;
case '1' : print_scr("changing mode");
turn_fan_on();
apply_brakes();
engine_off();
break;
case '2' : print_scr("2"); break;
case '3' : print_scr("3"); break;
default: delay_ms(200);
}
- Código:
switch (key) {
case 'a' :
case '1' : print_scr("changing mode");
turn_fan_on();
apply_brakes();
engine_off();
break;
case '2' : print_scr("2"); break;
case '3' : print_scr("3"); break;
default: delay_ms(200);
}
The 'if - else' construct is useful for small sections of decision code but if you find yourself creating a huge list of 'if else if else' statements then use a switch instead but beware of the 'break;' statement.
Note: You can super reduce an if statement using the conditional construct (expr ? true : false) see the C course for details of its use.
Switch statements are used extensively to create and control state machines as they conveniently separate state machine operation or "the state transition code" from the "state action code". State machines are used within windows programming, VHDL (diff. syntax but essentially the same idea) and embedded programming.
All use a switch type construct for clarity of programming intention.
Font: www.best-microcontroller-projects.com
Fórum de Electrónica - projectos, cursos, tutoriais, compra e venda, etc. em electrónica :: Electronic in general - Threads in English
Página 1 de 1
Permissões neste sub-fórum
Não podes responder a tópicos
|
|
Seg 27 Abr 2015 - 13:24 por Jose Manuel Borges
» Microchip MPLAB IDE - PIC16F84A
Sex 8 Ago 2014 - 19:29 por Electromonkeys
» Ajuda sobre curso de electronica
Seg 4 Ago 2014 - 13:57 por Nunes Pereira
» Procuro: Programdores em C, elaborar circuitos electrónicos. Trabalho remunerado
Qua 11 Jun 2014 - 14:07 por ricardo costa1986
» PORTA NOT
Dom 2 Mar 2014 - 13:40 por yoda
» Ajuda com Monitor Philips190tws
Qui 28 Nov 2013 - 1:28 por kagareu
» Estação de Retrabalho não derrete a solda
Sáb 12 Out 2013 - 17:10 por itacipri
» Plataforma para cálculo de tempo de voo
Sáb 27 Jul 2013 - 4:06 por diogofsousa92
» Prestação serviços projeto eletronica""
Sex 26 Jul 2013 - 15:24 por Mega_Migas
» l7812cv
Seg 15 Jul 2013 - 13:06 por boleiro