MISRA C states the following rationale:
“A single point of exit is required by IEC 61508 and ISO 26262 as part of the requirements for a modular approach.
Early returns may lead to the unintentional omission of function termination code.
If a function has exit points interspersed with statements that produce persistent side effects, it is not easy to determine which side effects will occur when the function is executed.”
Note that the MISRA C rule is merely advisory, meaning it is a recommendation and not a hard requirement (i.e. it’s a “should” and not a “shall”).
It's a bit like an operating system write-protecting pages. Sometimes you write-protect pages that the process really shouldn't write to, like shared libraries or something like that. But sometimes you write-protect pages that you actually expect a program to write to, like memory-mapped pages, because then when the write happens it triggers something else (like copy-on-write or marking a page dirty or something).
Rules like "Don't use dynamically allocated memory" are one example of this -- not that they really expect you never to do it, but that marking it "Required" is a way to force you to document how you plan to make it safe.
Similarly, if it's easier to rearrange a function to have only a single exit point than to explain why you need multiple exit points, just rearrange it; you really need multiple exit points, just document why.
profile_begin("func");
a = temp_arena_begin();
// ... code
temp_arena_end();
profile_end();I wish we could get an update on these rules, but this issue has been brought up many many times bwfore and has always been brushed away without a proper analysis.
I would not be in the least surprised if someone has a compiler/transpiler from a higher level language to some C code which checks all MISRA boxes.
Otherwise this leads to duplication of cleanup code similar to
allocate_something()
..
if failed(foo) {
deallocate_something()
return FAILED;
}
..
deallocate_something()
return SUCCESS;Or hopefully, eventually, in C, thanks to the tireless efforts of JeanHeyde Meneide:
https://thephd.dev/just-put-raii-in-c-bro-please-bro-just-on...
Now I'm really curious, doesn't that mean some valid C++ code would fail to link for having multiple definitions of the same symbol??
I would expect name mangling to be a bijection from function prototype to string.