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.

Participe do fórum, é rápido e fácil

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.
Fórum de Electrónica - projectos, cursos, tutoriais, compra e venda, etc. em electrónica
Gostaria de reagir a esta mensagem? Crie uma conta em poucos cliques ou inicie sessão para continuar.
Últimos assuntos
» Ajuda para mesa de mistura BEHRINGER Eurorack 2442Fx-Pro
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySeg 27 Abr 2015 - 13:24 por Jose Manuel Borges

» Microchip MPLAB IDE - PIC16F84A
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySex 8 Ago 2014 - 19:29 por Electromonkeys

» Ajuda sobre curso de electronica
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySeg 4 Ago 2014 - 13:57 por Nunes Pereira

» Procuro: Programdores em C, elaborar circuitos electrónicos. Trabalho remunerado
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptyQua 11 Jun 2014 - 14:07 por ricardo costa1986

» PORTA NOT
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptyDom 2 Mar 2014 - 13:40 por yoda

» Ajuda com Monitor Philips190tws
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptyQui 28 Nov 2013 - 1:28 por kagareu

» Estação de Retrabalho não derrete a solda
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySáb 12 Out 2013 - 17:10 por itacipri

» Plataforma para cálculo de tempo de voo
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySáb 27 Jul 2013 - 4:06 por diogofsousa92

» Prestação serviços projeto eletronica""
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySex 26 Jul 2013 - 15:24 por Mega_Migas

» l7812cv
When Should You Use 'switch' Instead of 'if-else' in C...‏ EmptySeg 15 Jul 2013 - 13:06 por boleiro

Quem está conectado?
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
 
 

Resultados por:
 


Rechercher Pesquisa avançada


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

Ir para baixo

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

Mensagem  joseflor Sáb 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
joseflor
joseflor
Nível 3
Nível 3

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

http://www.ozflor.com/eletrokit/

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos