2024-10-22 07:47 AM
This is a question about programming style, preferences, efficiency, and risk.
We are working on a state machine were multiple conditions are checked for a potential state transition. We are debating what is better, safer, more efficient, or simply more elegant: goto LABEL, or if else() blocks? The goto statement is simple, but if else() blocks are perhaps more robust in a team environment. See options 1 and 2 below. What do you recommend? Thanks!
Option 1:
if (condition_1 true)
{
[do something]
goto END_OF STATE;
}
if (condition_2 true)
[do something]
goto END_OF STATE;
Option 2:
if (condition_1 true)
[do something]
else if (condition_2 true)
{
[do something]
}
Solved! Go to Solution.
2024-11-13 07:58 AM
Andrew Neil , Pavel A. , PGump.1 : Thank you again for your helpful feedback. I wanted to conclude this conversation with the following comments.
I studied these two C-programming guidelines re. goto:
* MISRA C:2 012, Guidelines for the use of the C language in critical systems, March 2013.
* Barr Group, Embedded C Coding Standard.
Both guidelines advise against using the goto statement: "Unconstrained use of goto can lead to programs that are unstructured and extremely difficult to understand." However, both guidelines accept goto under certain conditions, in particular for "helping to minimize visual code complexity".
I paraphrase the conditions (without claiming completeness):
* Use goto only within the same block or function. Don't jump outside of that block/function.
* No 'back' jumps, only forward jumps.
These are my personal two additions:
* Use only one goto label within a single block or function.
* All goto statements should be visible on one screen or one page (if printed).
I am interested in your thoughts and experience. Please comment.
2024-11-13 08:37 AM
> both guidelines accept goto under certain conditions, in particular for "helping to minimize visual code complexity".
Again, try to post this in any massively C forum - especially Linux kernel ))
In Linux code base you will see a lot of goto's, with purpose to reduce cyclomatic complexity (and "minimize visual code complexity" as useful side effect). These goto's often jump out of blocks, the only rule is not to jump backwards.
Better languages (incl. C++) do not need this, but we're discussing C.
As for one screen or page... it obviously varies with font size and line interval. Not feasible to limit. My younger fellows got 3 monitors on their desks, two of them rotated vertically. Their "page length" is twice as much as mine.
Bottom line: Reject BS. If unsure - find a good consultant/coach/architect.