enum with unsigned char size

Discussion in 'C Programming' started by pozz, Jul 2, 2003.

  1. pozz

    pozz Guest

    Hi all,
    I want to use enum in this way:

    typedef enum {
    FIRST=1,
    SECOND,
    THIRD,
    FORTH,
    } order_t;

    Now, if I declare a variable such as:
    order_t n;
    compiler consider n as an integer (2 byte in a 16 bit environment).

    If I use only 4 values in an enumeration, n can be a simple unsigned
    char, i.e. sizeof(n)=1. Is it possible to use enumeration and to
    specify byte-length of that enumeration?

    I know that I can write:
    typedef enum {
    .... (as before)
    } order_t;
    unsigned char n;

    ....
    n=FIRST;
    ....

    But in that way I lose the link between variable and enumeration.
     
    pozz, Jul 2, 2003
    #1
    1. Advertisements

  2. pozz

    Jack Klein Guest

    There's a good chance that your compiler offers some option to do
    this.
    No standard way. The standard doesn't place any real requirement on
    the type used when you define a value of an enumeration type. It is
    allowed to use any type which can contain all of the defined values.
    So it could decide to use a char or unsigned char, but it is not
    required to. And there is no standard way to do what you want.
    Again, consult your compiler documentation and see if it offers an
    option to do what you want. But even if it does, remember that it's
    not standard and not particularly portable.

    --
    Jack Klein
    Home: http://JK-Technology.Com
    FAQs for
    comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
    comp.lang.c++ http://www.parashift.com/c++-faq-lite/
    alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
     
    Jack Klein, Jul 2, 2003
    #2
    1. Advertisements

  3. pozz

    Micah Cowan Guest

    There is no rael link between them anyway, other then the textual hint
    given to the human reader of the source. This could easily be solved
    with a comment:

    /* order_t n; */
    unsigned char n;

    HTH,
    -Micah
     
    Micah Cowan, Jul 4, 2003
    #3
    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.