Electronics > Microcontrollers

Forcing enum to be of a specific size

<< < (2/2)


--- 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.

It's available since C++11.

Thank you all! :)

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{

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":

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.


[0] Message Index

[*] Previous page

There was an error while thanking
Go to full version