Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enums

An enum gives names to a set of related integer constants. Code that says Blue instead of 10 explains itself, and the enum's name doubles as a type for variables and parameters that hold one of the values.

'' An enum names a set of related integer constants. Values count up
'' from 0, or on from the last value given.
enum Colour
    Red
    Green
    Blue = 10
    Violet
end enum

print "Red ="; Red; ", Green ="; Green; ", Blue ="; Blue; _
      ", Violet ="; Violet

'' A variable of the enum's type holds one of its values. The members
'' can be written plainly or through the enum's name.
dim as Colour wall = Colour.Blue
print "wall ="; wall
wall = Green
print "wall ="; wall

'' select case reads well with enum members.
function Describe( byval c as Colour ) as ustring
    select case c
    case Red, Violet
        return "warm"
    case Green, Blue
        return "cool"
    case else
        return "unknown"
    end select
end function
print "Violet is "; Describe( Violet )

'' An explicit enum must always be qualified, so its short member
'' names cannot clash with anything else.
enum Level explicit
    Low = 1
    Medium
    High
end enum
dim as Level volume = Level.High
print "volume ="; volume; ", and High - Low ="; Level.High - Level.Low

'' An enum value converts to an integer freely.
dim as int32 n = Level.Medium
print "Medium as an int32:"; n

'' The other direction is not checked: any integer fits.
wall = 42
print "wall ="; wall; " is "; Describe( wall )

Output

Red = 0, Green = 1, Blue = 10, Violet = 11
wall = 10
wall = 1
Violet is warm
volume = 3, and High - Low = 2
Medium as an int32: 2
wall = 42 is unknown

The first member is 0 unless it is given a value, and each member after it is one more than the one before. Blue = 10 restarts the count, so Violet is 11.

A member can be written on its own, Green, or qualified with the enum's name, Colour.Blue. Plain names are shorter, but when two enums share a member name only the qualified form says which one you mean. An explicit enum must always be qualified: in the Level example, a bare High is error TKO0743: 'high' is not declared. That makes short member names safe.

Enum values are integers. They print as numbers, compare with = and <, take part in arithmetic, and convert to an int32 without a cast. select case with one case per member is the usual way to act on one.

Pitfall

An enum variable accepts any integer. wall = 42 compiles even though no member of Colour is 42. That is why Describe has a case else: a value that arrived from a file or a calculation may not be a member at all.

Activities

  1. Add Orange between Red and Green and predict every value printed.
  2. Write a function that returns the Level one step above its argument, staying at High at the top.