I’m using a State Machine task to handle the flow of my program. When a state is selected (other than STAND BY), the State Machine wake up the associated task with the “xTaskNotifyGive” function as all other tasks are locked by “ulTaskNotifyTake( pdTRUE, portMAX_DELAY);”
During the execution of those state-related tasks, a problem can happen and the state-related task has to stop. In order to do that, a Safety task set a flag “ContinueTask”. In the state-related task, we regularly check this flag. If it is false, the code following won’t be executed.
For the moment, the structure of the code look like this:
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally){
//some code
}
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally){
//some code
}
...
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally){
//some code
}
The problem is that if the flag is set up the first time we check it, it will still check it for the next part of the code.
On way to solve this is to use a cascade of if/else statements like this:
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally){
//code
}
else{
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally){
//code
}
else{
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally){
//code
}
else{
....
}
}
}
But if we check this flag a lot of time if the task, the number of indentation will be really high and it won’t be readable.
I was wondering if, in this case, it’s possible to use the “goto” statement, like this:
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally) goto exitTask;
//some code
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally) goto exitTask;
//some code
...
ContinueTaskInternally = ContinueTaskCopy();
if (ContinueTaskInternally) goto exitTask;
//some code
exitTask:
//code before exiting task
What do you think about it? I made some research about those "goto" statment but I was not able to determine if it is ok to use as some people disagree on this subject without giving extra explenation why.
To me, this is a good situation to use short circuit boolean logic.
That is: If the flag is ever set to false
, the second part of the &&
expression will not get evaluated. The function ContinueTaskCopy()
will not be run.
As long as the flag is true
, all code will run.
As soon as the flag is false
, it will skip all the if-statements and all the ContinueTaskCopy
statements until the end of the function.
The makes your code look like:
bool ContinueTaskInterally = true;
ContinueTaskInternally = ContinueTaskInterally && ContinueTaskCopy();
if (ContinueTaskInternally){
//some code
}
ContinueTaskInternally = ContinueTaskInterally && ContinueTaskCopy();
if (ContinueTaskInternally){
//some code
}
...
ContinueTaskInternally = ContinueTaskInterally && ContinueTaskCopy();
if (ContinueTaskInternally){
//some code
}