0

On an embedded system, running freertos, is there any reason why you would not have a blocking function inside a case of a switch statement?

For example, a thread running through a state machine and one of the states is a wait for a task notification.

Typically I've done this with if-else's but is there any advantage or disadvantage to making it a switch case?

Using cpp17 and avoiding STL.

Edit: blocking function, i.e. one that sits forever until it gets a notification, such as xTaskNotifyWait(...)

Example:

switch (state)
{
case state1:
  foo();
  break;
case state2:
  xTaskNotifyWait(...);
};

vs

if (state == state1)
{
  foo();
}
else if (state == state2)
{
  xTaskNotifyWait(...);
}

TIA

1 Answers1

2

You can use either a switch or if statement. There isn't much a difference. You can have blocking calls in either of them.

I've heard that switch cases use hash tables but if-else doesn't. I'm not sure if there are differences in the asm code, and what impact that would have on code size, speed, etc.

See this to understand the difference between switch and if statement. I am quoting one of the answer below:

The main difference is that switch despatches immediately to the case concerned, typically via an indexed jump, rather than having to evaluate all the conditions that would be required in an if-else chain, which means that code at the end of the chain is reached more slowly than code at the beginning.

That in turn imposes some restrictions on the switch statement that the if-else chain doesn't have: it can't handle all datatypes, and all the case values have to be constant.

With a switch construct, you can use descriptive enum for your case label which says that this state is meant to be blocking. I would personally use a switch construct as the case label can be descriptive.

enum state_e {
    INIT,
    WAITING_FOR_EVENT
};

switch (state) {
case INIT:
{
  foo();
  state = WAITING_FOR_EVENT;
  break;
}
case WAITING_FOR_EVENT:
{
  xTaskNotifyWait(...);
  // Change State
  break;
}
};
Community
  • 1
  • 1
abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • 1
    Thanks very much, I've always been told that switch statements should be a quick, get in and get out, but never knew why. I suspected it wasn't founded on anything and there is no real reason why you *shouldn't* block within a switch-case – GreenaGiant Jan 07 '20 at 17:51
  • Sure. If it answers your question, don't forget to accept it! Thanks – abhiarora Jan 07 '20 at 17:52