Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
use a table instead of switch case in C

How to replace switch case by a table in this case, please?

typedef enum
{   DIV_1 = 1,
    DIV_2,
    DIV_4 = 4,
    DIV_8 = 8,
    DIV_16 = 16
} eDiv_t;

eDiv_t Division;

uint32_t dividerValue;

    switch (Division)
    {

        case DIV_1:
            dividerValue = RCC_DIV_1;
        break;
        case DIV_2:
            dividerValue = RCC_DIV_2;
        break;
        case DIV_4:
            dividerValue = RCC_DIV_4;
        break;
        case DIV_8:
            dividerValue = RCC_DIV_8;
        break;
        case DIV_16:
            dividerValue = RCC_DIV_16;
        break;
        default:
            dividerValue = RCC_DIV_1;
        break;
    }

I don't know how to affect enum variables to an array and use it instead of switch case

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You may define your enum as consecutive integer values and index your array with this enum:

typedef enum
{   DIV_1 = 0,
    DIV_2,
    DIV_4,
    DIV_8,
    DIV_16,
    NB_DIV
} eDiv_t;

unsigned int dividerValue[NB_DIV] = {RCC_DIV1, RCC_DIV2, ..., RCC_DIV16};
over 4 years ago · Santiago Trujillo Relatório

0

In this specific case where eDiv_t can't be changed because it is used elsewhere, a lookup table can be made as:

RCC_t eDiv_to_RCC (eDiv_t ediv)
{
  static const RCC_t lookup [16+1] = 
  {
    [DIV_1]  = RCC_DIV1,
    [DIV_2]  = RCC_DIV2,
    [DIV_4]  = RCC_DIV4,
    [DIV_8]  = RCC_DIV8,
    [DIV_16] = RCC_DIV16,
  };

  return lookup[ediv];  // returns 0 if invalid input
}

This is very fast but consumes 17 * sizeof(RCC_t) which I assume is another enum, likely 8 to 32 bits large. Not that big, but this is an execution speed over .rodata size optimization. On the other hand the actual code will take much less space than the switch version.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda