Enumerations


You’ll notice the type of the fields type, and err, is int. This means they are represented by a single integer number.

The reason we pick int is because we will assign meaning to each integer value, to encode what we require. For example we can make a rule “If type is 0 then the structure is a Number.”, or “If type is 1 then the structure is an Error.” This is a simple and effective way of doing things.

But if we litter our code with stray 0 and 1 then it is going to become increasingly unclear as to what is happening. Instead we can use named constants that have been assigned these integer values. This gives the reader an indication as to why one might be comparing a number to 0 or 1 and what is meant in this context.

In C this is supported using an enum.

  1. /* Create Enumeration of Possible lval Types */
  2. enum { LVAL_NUM, LVAL_ERR };

An enum is a declaration of variables which under the hood are automatically assigned integer constant values. Above describes how we would declare some enumerated values for the type field.

We also want to declare an enumeration for the error field. We have three error cases in our particular program. There is division by zero, an unknown operator, or being passed a number that is too large to be represented internally using a long. These can be enumerated as follows.

  1. /* Create Enumeration of Possible Error Types */
  2. enum { LERR_DIV_ZERO, LERR_BAD_OP, LERR_BAD_NUM };