icp/oer/courses/c-newcomers/sections/04-supermarket/03-states/content.md

1.5 KiB

This is great. Each item can now take different amounts of time to be scanned, but when you have multiple cashiers, one can scan many "easy" items, while the other scans one slowly. So simply adding up the time won't cut it.

To prepare the program for more than one cashier, this needs to change. To stay on the topics of enums we will use a construct known as a finite-state-machine.

Knowledge

A finite-state-machine let's you easily define different behaviours depending on what state their are in. Basically you need a variable to track the state, in this case it is CurrentState and you need a way of implementing different behaviour based on the current state. For that you can simply use if statements.

If you have more than one condition you want to test on, for example three different states, you can use the else if statement. This allows you to first test if one thing is true and, if is not, you can test for the second condition. You can chain as many else if statements as you want.

if(condition1)
{
    // gets executed if condition 1 is true 
}
else if(condition2)
{
    // gets executed if condition1 is false and condition2 is true
}
else
{
    // gets executed if non of the conditions above are true
}

So our cashier has the state STATE_ready_for_item and STATE_scanning. These are represented as an enum.

Task

Your task will be to implement the state-machine with an enum, such that while scanning you only increment the time-step by one.