Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!