Fórum de Electrónica - projectos, cursos, tutoriais, compra e venda, etc. em electrónica
Este fórum migrou para aqui. Se quiser visitar o novo fórum, deverá clicar nesta frase.

Para serviços neste fórum use os botões em baixo.
Últimos assuntos
» Ajuda para mesa de mistura BEHRINGER Eurorack 2442Fx-Pro
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
Sab 12 Out 2013 - 17:10 por itacipri

» Plataforma para cálculo de tempo de voo
Sab 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

Quem está conectado
2 usuários online :: Nenhum usuário registrado, Nenhum Invisível e 2 Visitantes

Nenhum

[ Ver toda a lista ]


O recorde de usuários online foi de 66 em Qui 6 Jan 2011 - 0:00
Buscar
 
 

Resultados por:
 


Rechercher Busca avançada


When Should You Use 'switch' Instead of 'if-else' in C...‏

Ver o tópico anterior Ver o tópico seguinte Ir em baixo

When Should You Use 'switch' Instead of 'if-else' in C...‏

Mensagem  joseflor em Sab 4 Jul 2009 - 11:36

You can think of switch statements as if they are multiple sets of if statements.
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);
    } 
The above code performs in exactly the same way as the following code:
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 switch statement provide a far more elegant way of coding for multiple decision tests and is much more readable - imagine having even 10 or 20 "if" tests - reading that lot (and maintaining them is hard).

The other advantage is that the tested expres​sion(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);
    }
Accidentally leaving "break;" off at case 2 will make the code perform differently. Operation for cases 1 and 3 is
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);
  }
Here the value of the key being 'a' or '1' will trigger the code print_scr("changing mode"); break;

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);                   
    }     
A better way instead of duplicating code is to use "fall through" and this means maintaining code is easier, less bugs and the code works exactly the same as before.
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);                   
    }   
Summary

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

_________________
Happy soldering!
José Flor - OzFlor
Venda de componentes de electrónica
Loja EBR (Eletrônica BRasil)
Fórum oficial de electrónica de José Flor - OzFlor
avatar
joseflor
Nível 3
Nível 3

Mensagens : 273
Pontos : 3302
Reputação : 7
Data de inscrição : 08/11/2008
Idade : 53
Localização : Mangerton, NSW, Austrália

Ver perfil do usuário http://www.ozflor.com/eletrokit/

Voltar ao Topo Ir em baixo

Ver o tópico anterior Ver o tópico seguinte Voltar ao Topo


 
Permissão deste fórum:
Você não pode responder aos tópicos neste fórum