0

I have a structure like this

typedef enum {
    STATE_PAUSED = 0,
    STATE_RUN,
    STATE_COUNTING,
    STATE_PERIODIC,
} State_t;

And what I need is to extend for new states that make sens just locally. Basically I want to have a switch that handles both original me->State and extended one State.

So I thought to wrap all in a local union but I can't figure out how :) Of course, I will take care for overlapping values.

  typedef union{
        State_t OrigState;
        typedef enum {
            GPS_MCU_UART_DEFAULT = 10,
            }LocalState;
    }State;

    switch((State)(me->State))
    {
    case STATE_RUN:

        break;

    case GPS_MCU_UART_DEFAULT:

        break;

    }

Appreciate a little help.

yo3hcv
  • 1,531
  • 2
  • 17
  • 27
  • 1
    Try to remove the second occurrence of `typedef` and refer to some [C reference](http://en.cppreference.com/w/c) site. Enable all warnings & debug info in your compiler (e.g. `gcc -Wall -Wextra -g`). Read [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Basile Starynkevitch Aug 22 '18 at 16:52
  • Use anonymous enums, or simple `#defines`. Get rid of the union and the cast. – user3386109 Aug 22 '18 at 17:00

2 Answers2

3

As long as you don't need the enum to be a type, you can do this easily enough.

enum State{
    STATE_PAUSED = 0,
    STATE_RUN,
    STATE_COUNTING,
    STATE_PERIODIC,
    STATE_MAX // must be last
};

enum GPS_State{
    GPS_MCU_UART_DEFAULT = STATE_MAX,
    GPS_FOO,
    GPS_BAR
};

enum Other_State{
    OS_CORGI = STATE_MAX,
    OS_FOO,
    OS_BAR
};

This does mean that a variable that could store any of these states would need to be an int. I'm not sure that there is a way to do it while enforcing type safety.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
0

Well... thanks for negative votes (someone shall review that more carefully).

Seems that in C you just cannot extend enums. Thanks to this post, I found a trick that works perfect for me Warning : case not evaluated in enumerated type?

Cast switch to int, than cast old enum to new one so: - compiler will not complain about missing sw entry - compiler will not complain about unused xxx_t

Here is my solution in case anyone needs to "extend enums" in C

   typedef enum {
        GPS_MCU_UART_DEFAULT = 10,
    }xxx_t;


    switch((int)(xxx_t)(me->State))
    {
    case STATE_RUN:

        break;

    case GPS_MCU_UART_DEFAULT:

        break;


    }

I will give my vote to Tim, thanks!

yo3hcv
  • 1,531
  • 2
  • 17
  • 27