4

I was surprised when doing the following that no assembly is produced for the Enums:

enter image description here

I thought perhaps it would do something like:

Hello:
    .byte 0
Goodbye:
    .byte 1

It seems it only adds in the values when assigned to a var:

enter image description here

Why is this so? Why don't the 'enum values' get stored when declared (even if I set Hello=1)? Example link: https://godbolt.org/z/xxnMvq.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 1
    They are stored in the compiler's data set so they can be used in other places in the program.`enum { Hello, Goodbye }` defines values, not a variable. Then, the `1` was used at label `c:` – Weather Vane Jan 09 '21 at 08:49
  • 3
    They're not stored; they are constants available at compiler level and simply translated to integers whenever they are used in statements. – Roberto Caboni Jan 09 '21 at 08:51
  • Related: [where and how are the values in each of the members of enum stored in C?](https://stackoverflow.com/questions/45845557/where-and-how-are-the-values-in-each-of-the-members-of-enum-stored-in-c), also [Why does the size of enum only correspond to the size of a single value?](https://stackoverflow.com/questions/65485445/why-does-the-size-of-enum-only-correspond-to-the-size-of-a-single-value). – dxiv Jan 09 '21 at 09:01
  • If you had done `enum {Hi, Bye} greeting;` then `greeting` would be a variable of type enum. – Erik Eidt Jan 09 '21 at 09:41

1 Answers1

7

An enum is not a variable, it is a type. The different enum labels are in fact constants. Being a type it requires no space in your final binary.

The compiler internally keeps a list of them and replaces every use of them with the constant they represent.

These values do however end up in the debugging info, if it is generated, so you can use them in your debugger.

koder
  • 2,038
  • 7
  • 10