Electronics > Microcontrollers

Forcing enum to be of a specific size

<< < (2/2)

SiliconWizard:

--- Quote from: Tagli on June 12, 2021, 05:00:03 am ---In C++, you can choose the underlying type for both classical enums and enum classes.


--- Code: ---enum class Number : uint8_t {Zero = 0, One = 1, Two = 2};
--- End code ---

--- End quote ---

I don't know enough C++ for judging if this is right or not. If anyone can tell which C++ std supports that? But if so, that is one nice feature.

Tagli:
It's available since C++11.
https://en.cppreference.com/w/cpp/language/enum

ricko_uk:
Thank you all! :)

DavidAlfa:
Probably everyone knows this from 1st of programming... Anyways, in normal C you can always cast the enum to an int of any size.
Ex. :

--- Code: ---typedef enum{
    opt_disable,
    opt_enable,
    opt_reset,
    opt_auto
}options_t;

options_t opts;

int main()
{
    if ((uint8_t)opts == opt_disable){
        printf("Option: Disabled, enabling....\r\n");
        opts = opt_enable;
    }
    return 0;
}

--- End code ---

Also gcc has it's own "attributes":
https://gcc.gnu.org/onlinedocs/gcc-3.3.2/gcc/Type-Attributes.html#Type%20Attributes

ajb:
I'm not sure what you're expecting the cast to do here?  Casting `opts` to uint8_t isn't going to change the allocated storage size.  The only way to do that is to declare `opts` as `uint8_t` (or whatever) instead of `options_t`, like I said earlier.  Using the packed attribute would affect the storage size of anything declared as `options_t`, but depends on the range of the enumerated values.  The cast won't meaningfully affect the comparison unless opts is stored at >8 bits and has bits set beyond the low byte, in which case it may break the comparison (depending on what you're trying to achieve).  Integer promotion rules will still apply as well.  ARM for example has zero- and sign-extension and word/half-word/byte load and store instructions so when required the compiler can transform 8 bit values into 32 bit values and vice versa as part of a load/store with no penalty and it'll be atomic as long as they're aligned.

Navigation

[0] Message Index

[*] Previous page

There was an error while thanking
Thanking...
Go to full version