I'm writing practice finite state machine code and can't wrap my head around the order of my "Switch" and "if" statements (which should come first).
Currently, I have it written as such:
task main()
{
// State variable default.
SystemStateType SystemState = State1;
While(1)
{
//Taken in from external sensors in real time
int reading;
if (reading == 0)
{
SystemState = State1;
}
else
{
SystemState = State2;
}
switch (SystemState)
{
case State1:
//actions
break;
case State2:
//other actions
break;
}
}
}
The code is intended to take sensor data in real time and respond accordingly. I realize that this is not actual functioning code, but I'm hoping that since the question is theoretical that my current code shown will suffice. Please let me know if I am missing anything.
Thank you!
can't wrap my head around the order of my "Switch" and "if" statements (which should come first).
Your switch
statement examines the value of the SystemState
variable, which is set through your if
statement. So the correct order is to have your if
statement, so that SystemStatevariable takes the desired value, and then examine the value of SystemState
in your switch
statement.
Suppose that you had if
and switch
statements the opposite way, like this :
task main()
{
// State variable default.
SystemStateType SystemState = State1;
While(1)
{
//Taken in from external sensors in real time
int reading;
switch (SystemState)
{
case State1:
//actions
break;
case State2:
//other actions
break;
}
if (reading == 0)
{
SystemState = State1;
}
else
{
SystemState = State2;
}
}
}
Then, in the switch
statement your SystemState
variable would always be State1
.
Of course, keep in mind that in the way you have written your code right now, reading
cannot receive any input. You need to give reading
a way to get a value.