C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

multiple function exits
Goto page 1, 2, 3 ... 20, 21, 22  Next
 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
Johannes Ahlmann
Guest





PostPosted: Fri Jun 10, 2005 4:34 pm    Post subject: multiple function exits Reply with quote



hi,

i hear again and again that in structured programming a function is
supposed to have exactly one entry and one exit point.

with a single entry point i have no problem, but i have often used
multiple exit points to reduce the maximum nesting depth of if/then/else
cases. therefore writing:


void hello(int a, int b)
{
if (0 == a)
return;

if (a == b)
return;

// complicated calculations HERE
}


instead of:


void hello(int a, int b)
{
if (0 != a) {
if (a != b) {
// complicated calculations
}
}
}


for such a short functions this obviously doesn't make much sense, but
when i have an if/then/else nesting with more then 4 hierarchies i like
to get rid of the easy cases early...

i agree that in a very long function this might make the function harder
to read, but personally i don't like deeply nested if/then/else's even
less.

so what would you say about the merits and disadvantages of multiple
exit points. does the compiler have problems optimizing it? which style
would/do you follow?

thx,

Johannes Ahlmann

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
meadori
Guest





PostPosted: Sat Jun 11, 2005 10:40 am    Post subject: Re: multiple function exits Reply with quote



Quote:
so what would you say about the merits and disadvantages of multiple exit points.
which style would/do you follow?
Personally I don't think using multiple exits is that big a deal. Like

any language feature you just have to be responsible with its use. The
merits and disadvantages are dependent on the problem begin solved. If
using them leads to a cleaner solution for the problem you are solving
then so be it.

Quote:
does the compiler have problems optimizing it?
Are far as a compiler (most if not all compilers I have run across) is

concerned there IS only one entry and one exit point. Just b/c you have
multiple returns in your code does not mean there will actually be
multiple exit points in the final code for the function. Consider your
first example:
void hello(int a, int b)
{
if (0 == a)
return;
if (a == b)
return;
// complicated calculations HERE
}
most compilers will end up producing something like:
void hello(int a, int b)
{
if (0 == a)
goto exit;
if (a == b)
goto exit;
// complicated calculations HERE
exit:
return;
}
So in reality there is only one entry and exit.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Swampmonster
Guest





PostPosted: Sat Jun 11, 2005 10:43 am    Post subject: Re: multiple function exits Reply with quote



Quote:
so what would you say about the merits and disadvantages of multiple
exit points. does the compiler have problems optimizing it? which style
would/do you follow?

If the compiler has problems optimizing it (compared to the nested
if-then-else code) than I'd say the compiler sucks.

What I think about multiple exit-points in general...
If an early return is used for error checking, chances are it should be
replaced by throwing an exception. But then again throwing an exception
is an exit-point too.
Error checking in general requires some way to exit a function early
under certain conditions (and maybe return some error-code or throw an
exception), and I think it's more clear to write "if(problem)
return/throw;" than to write "if(!problem) do_something(); else
return/throw;" - even if the "return" in the latter snippte will
sometimes be implicit and the whole "else" block can be avoided.

I think it's not about avoiding early returns at all costs, like it's
not about avoiding "gotos" or "breaks" at all costs. I think it's about
what's more readable and more clear - and IMHO there are situations when
early returns are OK, when "breaks" and "continues" are OK, and when
even "gotos" are OK. Especially (but not exclusively) when one cannot
use C++ exceptions for some reasons, and one still has to do heavy
error-checking.

I think if one's able to write nice & clear code he/she will know what
to use when, and if one's not able to write nice & clear code it won't
help much if he/she aviods some "bad words" like "return", "break",
"continue" and "goto" at all costs - it will sometimes even make things
worse.

And to answer your question in short: For handling special cases I use
"early returns" most of the time. For handling errors I prefer
exceptions, and if I can't use exceptions for whatever reason I use
"early returns".
(and if I e.g. have a loop iterating over a sequence of chars and I want
to skip white-spaces and process other chars, then I use
"if(isspace(ch)) continue;" -- because to me "if it's a white-space,
skip it. process everything else. goto next char." is a more natural way
to think than "if it's not a white-space, process it. goto next char.")

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Joshua Lehrer
Guest





PostPosted: Sat Jun 11, 2005 10:44 am    Post subject: Re: multiple function exits Reply with quote


"Johannes Ahlmann" <softpro (AT) gmx (DOT) net> wrote

Quote:
hi,

i hear again and again that in structured programming a function is
supposed to have exactly one entry and one exit point.

with a single entry point i have no problem, but i have often used
multiple exit points to reduce the maximum nesting depth of if/then/else
cases. therefore writing:


void hello(int a, int b)
{
if (0 == a)
return;

if (a == b)
return;

// complicated calculations HERE
}


instead of:


void hello(int a, int b)
{
if (0 != a) {
if (a != b) {
// complicated calculations
}
}
}



the former is superior to the latter.

Your function already may have multiple exit points. What if 'a' and/or 'b'
were custom types, and the operator== threw an execption?

joshua lehrer
factset research systems
NYSE:FDS



[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Florian Schwarz
Guest





PostPosted: Sat Jun 11, 2005 10:47 am    Post subject: Re: multiple function exits Reply with quote

Johannes Ahlmann wrote:

Quote:
with a single entry point i have no problem [...]

well, i don't think c gives you much of a choice there...

Quote:
void hello(int a, int b)
{
if (0 == a)
return;

if (a == b)
return;

// complicated calculations HERE
}

void hello(int a, int b)
{
if (0 != a) {
if (a != b) {
// complicated calculations
}
}
}

for such a short functions this obviously doesn't make much sense, but
when i have an if/then/else nesting with more then 4 hierarchies i like
to get rid of the easy cases early...

but it already makes it a bit easier to read, and you can see in the
first lines that invalid or special cases are taken care of.

Quote:
i agree that in a very long function this might make the function harder
to read, but personally i don't like deeply nested if/then/else's even
less.

i don't think so, i think it can make large functions much simpler and
thus easier to read. ok, what you probably shouldn't do is placing a
return deeply inside a nested if/else/switch or something like that.
also, i think it might make it harder to ensure that all buffers you
allocated are freed correctly for every exit point. but if you find
yourfelf writing a large, hard-to-read function, it is (IMHO) always a
good idea too re-think it, maybe you find parts that can easily be made
a function of their own. some small functions together can be quite
powerful, and make your code much easier to read.

Quote:
so what would you say about the merits and disadvantages of multiple
exit points. does the compiler have problems optimizing it? which style
would/do you follow?

that would be interesting indeed. personally, i can't think of a reason
why it should be harder to optimize, if you don't use multiple exit
points you also need jumps over your if/elses to the end of your
function. the compiler does not have to put all the return code
everywhere you write return, it could place it at the end of your
function and reference it by a jump. but i don't know it, just guessing.
maybe someone else can provide more information.

personally, i use multiple exit points, too. but i hope someone with a
different opinion will show up and explain me why he/she doesn't like
it, i'm sure there are good reasons.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
ben
Guest





PostPosted: Sat Jun 11, 2005 10:48 am    Post subject: Re: multiple function exits Reply with quote

The technique is called short circuiting. It doesn't comform with the
structured programming concept. but who cares? all we need is a piece of
clear code that does the work and is easy to understand. if short circuiting
makes code easier to write and easier to read, go ahead!

ben



[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Peter Schneider
Guest





PostPosted: Sat Jun 11, 2005 10:50 am    Post subject: Re: multiple function exits Reply with quote

Hi,

"Johannes Ahlmann" wrote

Quote:
hi,

i hear again and again that in structured programming a function is
supposed to have exactly one entry and one exit point.

with a single entry point i have no problem, but i have often used
multiple exit points to reduce the maximum nesting depth of if/then/else
cases. therefore writing:


void hello(int a, int b)
{
if (0 == a)
return;

if (a == b)
return;

// complicated calculations HERE
}


instead of:


void hello(int a, int b)
{
if (0 != a) {
if (a != b) {
// complicated calculations
}
}
}


for such a short functions this obviously doesn't make much sense, but
when i have an if/then/else nesting with more then 4 hierarchies i like
to get rid of the easy cases early...

i agree that in a very long function this might make the function harder
to read, but personally i don't like deeply nested if/then/else's even
less.

so what would you say about the merits and disadvantages of multiple
exit points. does the compiler have problems optimizing it? which style
would/do you follow?

I personally like to do exactly what you suggested here: exclude "all the
pathological cases" before the actual work is done. It usually simplifies
the main code.

I admit that I have once written a large function with many returns out of
the middle of it, when certain conditions were met, which became really
unmaintainable. That was a lesson to be careful with it.

A problem arises when a cleanup must be performed or a flag must be set etc.
when the function returns, no matter from where. It can be solved by
creating custom objects in the proper places that perform the cleanup in
their destructor which is called implicitly when the function is left, no
matter how. But this can be hard to understand for people who have never
seen the construction and need to maintain the code.

Regards, Peter



[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Dave Harris
Guest





PostPosted: Sun Jun 12, 2005 3:33 pm    Post subject: Re: multiple function exits Reply with quote

[email]softpro (AT) gmx (DOT) net[/email] (Johannes Ahlmann) wrote (abridged):
Quote:
i hear again and again that in structured programming a function is
supposed to have exactly one entry and one exit point.

This has been discussed here before; you may need to search back a few
years. Breaking out of loops was especially controversial. For what it's
worth, I agree with you and use multiple exits whenever convenient.

-- Dave Harris, Nottingham, UK.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
James Kanze
Guest





PostPosted: Sun Jun 12, 2005 5:02 pm    Post subject: Re: multiple function exits Reply with quote

Johannes Ahlmann wrote:

Quote:
i hear again and again that in structured programming a
function is supposed to have exactly one entry and one exit
point.

It's an occasional rule. I tend to agree, but the rule is
anything but systematic, and I know some very competent
programmers who strongly disagree with it.

Quote:
with a single entry point i have no problem, but i have often
used multiple exit points to reduce the maximum nesting depth
of if/then/else cases. therefore writing:

void hello(int a, int b)
{
if (0 == a)
return;

if (a == b)
return;

// complicated calculations HERE
}

instead of:

void hello(int a, int b)
{
if (0 != a) {
if (a != b) {
// complicated calculations
}
}
}

For this particular example, I'd write:

void
hello( int a, int b )
{
if ( a != 0 && a != b ) {
// complicated calculations...
}
}

Quote:
for such a short functions this obviously doesn't make much
sense, but when i have an if/then/else nesting with more then
4 hierarchies i like to get rid of the easy cases early...

If you have an if/then/else nesting with more than four
hierarchies, then the function is doing way too much. And
that's very bad, regardless of your opinion concerning the
single entrance single exit rule.

Quote:
i agree that in a very long function this might make the
function harder to read, but personally i don't like deeply
nested if/then/else's even less.

so what would you say about the merits and disadvantages of
multiple exit points. does the compiler have problems
optimizing it? which style would/do you follow?

I generally follow single entry/single exit. For my personal
definition of single entry/single exit, of course: I allow ?:
operators in the return statement (which some would argue is not
single entry/single exit), and I use exceptions (which definitly
create mutliple exits in fact).

In practice, I would say that if your functions are long enough
for it to make a difference, *that*'s a problem. And that
despite my preference for single entrance/single exit, I'd much
rather deal with functions of five lines, with multiple exits,
than functions of 50 lines which rigorously follow the single
entrance/single exit philosophy.

(I might add that there are intermediate variants as well. In
the days before templates, I knew of more than one programmer
who followed the single entrance/single exit rule in the main
part of the function, but used a premature exit at the top of
the function for things like pre-condition variations. A
situation not unlike exceptions.)

--
James Kanze mailto: [email]james.kanze (AT) free (DOT) fr[/email]
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 pl. Pierre Sémard, 78210 St.-Cyr-l'École, France +33 (0)1 30 23 00 34

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
moy@polyspace.com
Guest





PostPosted: Mon Jun 13, 2005 4:16 pm    Post subject: Re: multiple function exits Reply with quote

Johannes Ahlmann wrote :
Quote:
i hear again and again that in structured programming a function is
supposed to have exactly one entry and one exit point.
so what would you say about the merits and disadvantages of multiple
exit points.

Hi,

I see the disadvantage of possibly having no exit point for some
executions. That is, a function returning a value might end-up
returning garbage values in some cases, because the execution reached
the closing brace of the function's body with no return before.

Take your example, and make it return "int":

int hello(int a, int b)
{
if (0 == a)
return 0;

if (a == b)
return 0;

// complicated calculations HERE, that may not "return"
// in some cases, but simply terminate without "return"
}

It is safer in this case to initialize the return value to some
acceptable "default" state, change that state appropriately, and
return it just before the end of the function's body:

int hello(int a, int b)
{
int performed = 0;
if (0 != a && a != b) {
// complicated calculations HERE, that may change "performed"
}
return performed;
}

You can even keep early returns.

In fact, this is a related problem to what you've said, but not
the same, since it occurs with single exit functions too, but I think
less frequently.

Yannick


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Keith H Duggar
Guest





PostPosted: Mon Jun 13, 2005 10:44 pm    Post subject: Re: multiple function exits Reply with quote

Johannes,

I run into this design decision often in complicated
numerical codes. Often I find that in trying to reduce the
number of exit points the design actually becomes simpler
and more robust. Often it also reveals or clarifies holes in
the logic of the algorithm.

Can you provide a concrete example of a function where you
have used multiple exit points? It might make for an
interesting case study.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Andrei Alexandrescu (See
Guest





PostPosted: Tue Jun 14, 2005 9:45 am    Post subject: Re: multiple function exits Reply with quote

Keith H Duggar wrote:
Quote:
Can you provide a concrete example of a function where you
have used multiple exit points? It might make for an
interesting case study.

Just searching for "return" in whatever file was on top:

static void print_collection(const float *b, const float *const e,
const char *const s = " ") {
if (b == e) return;
printf("%.2g", *b);
++b;
for (; b != e; ++b) {
printf("%s%.2g", s, *b);
}
}


Andrei, the one who thinks SESE sucks

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Nicola Musatti
Guest





PostPosted: Tue Jun 14, 2005 7:31 pm    Post subject: Re: multiple function exits Reply with quote



Andrei Alexandrescu (See Website For Email) wrote:
Quote:
Keith H Duggar wrote:
Can you provide a concrete example of a function where you
have used multiple exit points? It might make for an
interesting case study.

Just searching for "return" in whatever file was on top:

static void print_collection(const float *b, const float *const e,
const char *const s = " ") {
if (b == e) return;
printf("%.2g", *b);
++b;
for (; b != e; ++b) {
printf("%s%.2g", s, *b);
}
}

static void print_collection(const float *b, const float *const e,
const char *const s = " ")
{
if (b != e)
{
printf("%.2g", *b);
++b;
for (; b != e; ++b)
{
printf("%s%.2g", s, *b);
}
}
}

There, *now* it looks the way it should!

Quote:
Andrei, the one who thinks SESE sucks

SESE rules!

Nicola Musatti


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
kanze@gabi-soft.fr
Guest





PostPosted: Tue Jun 14, 2005 7:32 pm    Post subject: Re: multiple function exits Reply with quote

Andrei Alexandrescu (See Website For Email) wrote:
Quote:
Keith H Duggar wrote:
Can you provide a concrete example of a function where you
have used multiple exit points? It might make for an
interesting case study.

Just searching for "return" in whatever file was on top:

static void print_collection(const float *b, const float *const e,
const char *const s = " ") {
if (b == e) return;
printf("%.2g", *b);
++b;
for (; b != e; ++b) {
printf("%s%.2g", s, *b);
}
}

void
print_collection(
float const* begin,
float const* end,
char const* separator = " " )
{
for ( float const* current = begin ; current != end ; ++
current ) {
printf( "%s%.2g", current == begin ? "" : separator,
*current ) ;
}
}

Or the variant I often use:

void
print_collection(
float const* begin,
float const* end,
char const* separator = " " )
{
char const* prefix = "" ;
for ( float const* current = begin ; current != end ; ++
current ) {
printf( "%s%.2g", prefix, *current ) ;
prefix = separator ;
}
}

--
James Kanze GABI Software
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Antoun Kanawati
Guest





PostPosted: Tue Jun 14, 2005 7:37 pm    Post subject: Re: multiple function exits Reply with quote

Keith H Duggar wrote:
Quote:

Can you provide a concrete example of a function where you
have used multiple exit points? It might make for an
interesting case study.

I would like to see an example with multiple Entry points, in
some recent vintage programming language; assembly language does
not count.

--
A. Kanawati
[email]NO.antounk.SPAM (AT) comcast (DOT) net[/email]

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Goto page 1, 2, 3 ... 20, 21, 22  Next
Page 1 of 22

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.