Why do I need this strange listing for enum arithmetic?

I have this piece of code:

typedef enum myEnum_e
{
    VAL0,
    VAL1
} myEnum;

void func(void)
{
    myEnum val = (myEnum) 0;

    while(/*Do something*/)
    {
        val = val + ((myEnum)1); // <= Warning here
    }
}

This piece of code generates a warning:

enumerated type mixed with another type

To clear this, I ended up:

void func(void)
{
    myEnum val = (myEnum) 0;

    while(/*Do something*/)
    {
        val = ((myEnum) val + 1); // <= NO Warning here
    }
}

Can someone say why the first form is wrong? I feel that the second is less significant than the first. I mean, I would rather read:

Add 1 read as value myEnumto val(and save the result to val)

Than

Store val val + 1asmyEnum

Note. This is the TI C28x compiler (for the MCU TI C2000).


Edit:

My real application is defining UART user communications for firmware. So here is what I did:

typedef enum e_frame
{
    FRAME_A,
    FRAME_B,
    FRAME_C,
    FRAME_COUNT
} frame_e;

typedef enum e_frameId
{
    FRAMEID_A = 0x0A,
    FRAMEID_B = 0x42,
    FRAMEID_C = 0xFF
} frameId_e;


const frameInfo_s FramesInfo[FRAME_COUNT] =
{
        [FRAME_A] =
            {
                    .id = MCM_FRAMEID_A,
                    // And other stuff
            },
        [FRAME_B] =
            {
                    .id = MCM_FRAMEID_B,
                    // And other stuff
            },
        [FRAME_C] =
            {
                    .id = MCM_FRAMEID_C,
                    // And other stuff
            }
}

Finally, the ID function for frame_e:

frame_e UAR_FrameId2Frame(frameId_e id)
{
    frame_e frame = (frame_e) 0;

    while(FramesInfo[frame].id != id && frame < FRAME_COUNT)
    {
        frame = (MCM_frames_e)(frame + 1);
    }

    return frame;
}
+4
3

:

#include <stdio.h>

typedef enum myEnum_e
{
    VAL0,
    VAL1
} myEnum;


int main (int argc, char *argv[]) {
    myEnum val = 0;

    while( 1 /*Do something*/)
    {
        val =  val + 1;
    }
    return 0;
}

: GCC 4.2.1

: gcc -Wall -pedantic x.c

+1

, . C , , . . , , . enum, 1.

0

, , , .

, . , .

, 3 VAL0?

Think about it, what does it mean? You declared a listing, but the value you received is no longer a valid listing. The reason for using the enumeration is mainly because you want to limit the number of possible values ​​for the sequence number.

In your situation, it makes sense to have constants like VAL0 and VAL1.

Or, if you needed to iterate over the list, you can do this:

typedef enum myEnum_e
{
    VAL0,
    VAL1,
    // ...
    VAL66
} myEnum;

for(int i=VAL0; i<=VAL66; i++) {
  // do something here
}
-1
source

All Articles