enums and bit fields

Discussion in 'C Programming' started by Randy Budd, Jun 22, 2010.

  1. Randy Budd

    Randy Budd Guest

    can I use enums for a bit field (as opposed to an int)?

    is it valid at all?

    is it undefined across platforms? (i.e. not very portable)

    is it ok as long as the enums don't overrun the bitfield?

    is an enum signed or unsigned?

    EX

    typedef enum {
    TYPE_A, TYPE_B, TYPE_C,
    } Type;

    typedef struct {
    unsigned int aType:5;
    Type bType:5; /* is this O.K. ? */
    unsigned int aFlag:1;
    } Struct;

    main()
    {
    Struct a;

    a.aType = TYPE_B;
    a.bType = TYPE_C;

    ....

    }
     
    Randy Budd, Jun 22, 2010
    #1
    1. Advertisements

  2. Not portably. C99 6.7.2.1p4:

    A bit-field shall have a type that is a qualified or unqualified
    version of _Bool, signed int, unsigned int, or some other
    implementation-defined type.
    These are all implementation-defined.

    [...]
    Make this "int main(void)".

    [...]
     
    Keith Thompson, Jun 22, 2010
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.