3 ms·
MISRA doesn't ban it, that rule is only Advisory which pretty much means you can ignore it. Rules 15.2 and 15.3 (Required) define how you can use goto if you de
by metarox 5y ago
MISRA doesn't ban it, that rule is only Advisory which pretty much means you can ignore it. Rules 15.2 and 15.3 (Required) define how you can use goto if you decide to use it.
Rule 15.2 The goto statement shall jump to a label declared later in the same function (forward gotos only)
Rule 15.3 Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statement (can't jump a scope level lower than current [jumping in an if block from outside] or from 2 identical but separate scopes [from one if to another independent if])
Personally, I like the Linux kernel model for goto which fits these constraints. Reading code like a shopping list and jumping to the proper cleanup point is much easier to read than having 3-4 if else levels and having to scroll the screen to make sure resources are cleaned at all levels, etc. Nothing beats making the mental model of code smaller to keep in my head and readability in my book so I'll take that approach over applying holy war-ladden absolute rules.
Note that using gotos also jives well with Rule 15.5 requiring a single exit point in functions (Advisory).
Edit: as panax wrote somewhere in this thread, CERT-C rules even recommend it
- lelanthran 5y agoI'm familiar with MISRA (embedded dev), I only wanted to point out that the MISRA rules in no way justifies a blanket ban on gotos. The ban (in the case of C, anyway) is almost always the result of someone's completely subjective opinion that gotos are bad.
- metarox 5y agoI fully concur on that last statement!
- panax 5y agoA customer put a blanket ban on goto because they decided to require MISRA 15.1 and want(need) to be compliant as well as having their own interpretation of MISRA. They also put a blanket ban on multiple returns (15.5). While it is true MISRA does not intend a blanket ban on these (and a blanket ban is contrary to the rationale for these rules), it often leads to a blanket ban and when these two in particular happen together it leads to awful code. I've seen this from multiple customers in different industries.
- mytailorisrich 5y agoIt's easier to 'ban' it and then to make exceptions on a case by case basis when not using goto make things worse. That has three practical benefits: It's clear (which is an underrated quality), it forces people to structure their code accordingly, and it prevents endless discussions (another very valuable quality). Otherwise, in my experience the use of goto tends to creep up and every occurrence leads to discussions in code review. So it's not that those decisions are subjective is that they are practical and workable. Especially, if you are defining practices for contractors to follow it is beneficial to keep those rules simple and clear as they will form contractual obligations.