The enum Construct

Somehow, we have to represent all the instructions that our machine is going to be capable of understanding. Of course when they are in the memory of our machine, they need to be stored as single bytes. Thus each instruction needs to be represented by a number. Since a byte gives us 2^8 = 256 possibilities, each instruction needs to be encoded by a number from 0 to 255.

However, it would be nice to not have to remember exactly which number coded for each individual instruction. One way of accomplishing this, is with an enum construction. This is a C expression for automatically assigning numbers to different symbols in order from 0 upwards.

In our program, we accomplish our aim by including an enum, which we call opcodes, and which contains a list of names of instructions, which are then automatically assigned numbers in order, starting from 0, by C. We write:

enum opcodes

where we have left out many of the instruction opcodes for brevity.

C now treats opcodes as a user defined type. A variable of this type can then store the values LDA, LAX, LDI, etc. The upshot of all this, is that we can refer to our instructions by name instead of by number.

Since C represents these opcodes as integers, we can also treat opcodes as integers too if we need to, though one must be careful not to make assumptions about which integers are assigned to which elements of an enum, since some compilers might number things differently.

Sometimes when we want to use an enum, we want certain numbers to refer to certain elements of the enum. For example, suppose that we wanted to introduce an additional pretend instruction called INV for invalid and we wanted it to specifically have the value 255. We could do this by including INV = 255 in our enum. Numbering of subsequent elements of the enum, if there were any, would then proceed from 256 onwards.