Enum

Enum is a mean to assign automatically successive values to constants, and thus to give significant names to codes and numbers.
For example a painter program have to deal with brush, pencil, fill, shadow, etc...
Rather than to designate each tool by a number in messages between components
of the program, an enum is created:

 enum
     BRUSH, PENCIL, FILL, SHADOW, etc...
 /enum

The enum structure may have also the simplified syntax:

 enum BRUSH, PENCIL, FILL, SHADOWN, etc...

The "let" keywords is useless here and may be omitted since there is no
condition after the enum keyword.

The identifiers are assigned the value from 0 to n - 1, if their number is n.
Thus, the enum above is equivalent to:

 constant integer BRUSH = 0
 constant integer PENCIL = 1
 constant integer FILL = 2
 constant integer SHADOW = 3
 etc.

It is possible to restart the numbering at any position in the list:

Example of renumbering. enum BRUSH, PENCIL = 4, FILL, SHADOW, etc..

print BRUSH, PENCIL, FILL, SHADOW
Displays: > 0 4 5 6


Enum allows to assign integer, real or text literals. A value is assigned
with a colon (not the equal code that changes the numbering), and if nothing
is associated, an integer is assigned.

Example of assignments. enum
ZERO : "a0" ,
ONE : "a1" ,
TWO: "a2",
THREE ,
FOUR : 3.15 ,
FIVE
/enum

print ZERO, ONE, TWO, THREE, FOUR, FIVE
Displays: > a0 a1 a2 0 3.15 1


A more explicit example...
Codes of access modes to file are assigned the name of the corresponding operation, into an enum structure.

Example of coding. enum READ:"r", WRITE:"w", APPEND:"a"

file f = fopen("infile", READ)
file g = fopen("outfile", WRITE)

Use enums to make your programs more readable. This cost nothing: each name
will be replaced by the value in the generated Php or C++ target file!
Of course this doesn't make the generated code more readable ;-)


 Exercises

 

1) Here is a list of constants of various types. Rewrite to a simpler code, thanks to an enum structure.
Then display the values int the a, b, c, d order.

constant int a = 0
constant int b = 4
constant real c = 0.5
constant int d = 3

Answer