Sheerpower Logo
E.6  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.
  • value1, value2, value3, ...: The named values within the ENUM, each assigned a sequential number starting from 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.).

Handling Errors and Limitations

Be aware that ENUM values in SheerPower are sequential, starting from 1. If your application requires non-sequential values, consider using a cluster with manually assigned values instead. Also, make sure to handle cases where an invalid ENUM value might be used by incorporating default cases in your Select Case statements.

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 fields in the ENUM. This can be useful for validating input or applying logic across all possible states.

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.
Wide screen