3

if I create an enum like so

enum test {
  a=0,
  b
};

Is a variable of type enum test stored as 1 bit in memory, as that's the minimum needed to represent it?

user189728
  • 278
  • 1
  • 10

2 Answers2

5

According to the language specification, the size of an enum is guaranteed to be at most the size of an integer. Keeping that in mind, the compiler is free to choose the actual size upon analyzing the source code.

Having said that, you can use https://godbolt.org/ to explore the asm output of various C compilers running on loads of different CPU architectures. From there, you can figure out the actual size on your specific configuration.

Elvir Crncevic
  • 525
  • 3
  • 17
3

No.

Well, compilers optimize it, but not for memory. Usually it's the native size for your CPU. Some compilers will let you request that it be optimized for memory instead of speed (GCC has -fshort-enums and __attribute__((__packed__)), for example), but they will not reduce storage down to a single bit.

For anything smaller than a byte you'd have to use a bitfield or bitmask, but even then all you can do is pack multiple values into a byte.

nemequ
  • 16,623
  • 1
  • 43
  • 62