Yosra MH
Yosra MH

Reputation: 159

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

Upvotes: 0

Views: 471

Answers (2)

Lundin
Lundin

Reputation: 214265

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.

Upvotes: 1

Guillaume Petitjean
Guillaume Petitjean

Reputation: 2718

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};

Upvotes: 2

Related Questions