Popup YouTube Video
Sheerpower Logo

Enum Statement


ENUM Statement in Sheerpower

The ENUM statement in Sheerpower allows you to define a set of related constants with automatically assigned sequential numbers. This is useful for creating state machines, categorizing options, or any situation where you need a clear, consistent, and easily maintainable set of named values.

Syntax

Enum enum_name: value1, value2, value3, ...

In this syntax:

  • enum_name: The name of the ENUM cluster.
  • name1, name2, name3, ...: The named values in the ENUM. When no explicit values are supplied, Sheerpower assigns the values automatically, starting with 1 and increasing by 1 for each following name.
  • name1=value1, name2=value2, name3=value3, ...: The named values in the ENUM with explicit numeric values. If a later name does not include an explicit value, Sheerpower assigns it the previous value plus 1.

Example: Traffic Light States

Enum traffic_light: red, yellow, green current_state = traffic_light->yellow select case current_state case traffic_light->red print "Stop" case traffic_light->yellow print "Get Ready" case traffic_light->green print "Go" case else print "Unknown State" end select // Print the number of fields in the enum print 'Number of fields: '; size(traffic_light,2)

Explanation

In this example, the ENUM statement defines three states for a traffic light, with red as 1, yellow as 2, and green as 3. The current state is set to yellow, and a Select Case statement determines the action to take based on the traffic light's current state.

The size(enum_name, 2) function returns the number of fields in the ENUM, making it easy to manage and iterate over the defined values.

Using ENUM improves code readability by replacing hardcoded numbers with meaningful names, reducing errors and making maintenance easier.

Best Practices

When defining an ENUM, use meaningful and consistent names for your values to make the code more readable. Avoid long names that could clutter the code, and try to keep the ENUMs simple and focused on one concept (e.g., states, categories, etc.).

Advanced Usage Tips

To iterate over ENUM values, you can use a loop combined with the size(enum_name, 2) function, which returns the number of names in the ENUM. This can be useful for validating input or applying logic across all possible states.

// Convert a text status into a numeric one mychoice$ = 'REJECTED' select case mychoice$ case nameof$(status->rejected) mystatus = status->rejected case nameof$(status->approved) mystatus = status->approved case nameof$(status->pending) mystatus = status->pending case else print "Unknown status: "; mychoice$ end select print 'status is ';mystatus
Hide Description

    

       


      

Enter or modify the code below, and then click on RUN

Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use.