Walter Roberson wrote:
Quote:
In article <88O8k.6711$cW3.3757@nlpi064.nbdc.sbc.com>,
Stephen Sprunk <stephen@sprunk.orgwrote:
>
Quote:
>Some programmers prefer to have only a single return point from each
>function; others prefer to return as soon as possible so that the
>bypassed code does not have to be indented. It's a matter of style,
>nothing more.
>
It is also an issue with ease of proving program correctness.
That's "ease" rather than "ability": since the semantics of
the language are fixed, given a program with multiple returns and
permission to create temporary storage areas [not a certainty for
embedded programming], one can automatically transform the
multi-return program into a single-return program by adding state
variables.
An optimizing compiler, though, could transform either form to the other
reasonably easily under the hood, using the "as if" rule.
This:
int foobar(int condition) {
if (condition)
return FOO;
return BAR;
}
Might be transformed into this:
int foobar(int condition) {
int retval;
if (condition)
retval = FOO;
else
retval = BAR;
return retval;
}
or this:
int foobar(int condition) {
int retval;
if (condition) {
retval = FOO;
goto end;
}
retval = BAR;
end:
return retval;
}
They all do exactly the same thing, and the compiler is free to
transform any one of them into either of the others (or something else
entirely) as long as the result is the same. While these are trivial
examples and likely all perform the same even if translated literally
without much optimization, more complicated examples _could_ see size or
speed benefits from being transformed.
Still, the primary audience for source code is humans, not compilers.
Use of common style and idioms makes code easier to understand and
maintain, even if the compiler doesn't need them or transforms your code
into something else entirely (which runs faster, but equally correctly).
Quote:
The result might not be at all pretty, though. And it could change the
detailed behaviour of a real-time program -- which is more of an issue
than it might sound at first, because proof of behaviour (e.g., maximum
event execution time) for real-time programs can often be quite
important.
Performance guarantees are outside the scope of the C standard, of
course. Proving correctness is a matter of logic; I'll submit that one
of the above constructions may be easier to prove correct than the
other, but proving which one is faster can only be done with empirical
testing. Thanks to modern optimizing compilers, it's virtually
impossible to guess which implementation of the same general algorithm
will be faster. For small values of N, it's not even possible to guess
which algorithm is fastest.
S