cppquester@googlemail.com wrote:
> A colleague told me that there is a rule about good stype that a
> function in C++ should have only one point of return (ie. return
> statement). Otherwise there might be trouble.
> I never heard about it and doubt it.
> Anybody heard of it?
Sure.
> What would be the advantage?
Don't know. Some people think it makes it easier to argue correctness. I am
not so sure about that, though. However, I can see the point: return
statements are like goto statements; they jump to the end of the current
routine. As with goto statements, you need to be careful.
[snip]
> bool f()
> {
> if( !pointer1) return false;
> pointer1->doSomething();
>
> if( !pointer2) return false;
> pointer2->doSomething1();
>
> return true;
> }
>
> vs.
>
> bool f()
> {
> bool retVal=true;
> if( pointer1)
> {
> pointer1->doSomething();
> }
> else
> retVal=false;
>
> if( pointer2)
> {
> pointer2->doSomething();
> }
> else
> retVal=false;
>
> return retVal;
> }
I am not really certain about that example. I tend to have multiple exits in
situations like this:
/*
triple is like pair, except that it has fields "first",
"second", and "third".
*/
template < typename A, typename B, typename C >
bool operator< ( triple< A, B, C > const & lhs,
triple< A, B, C > const & rhs ) {
// try deciding using first:
if ( lhs.first < rhs.first ) {
return ( true );
}
if ( rhs.first < lhs.first ) {
return ( false );
}
// first was tied. try second:
if ( lhs.second < rhs.second ) {
return ( true );
}
if ( rhs.second < lhs.second ) {
return ( false );
}
// first and second tied. try thrid:
if ( lhs.third < rhs.third ) {
return ( true );
}
if ( rhs.third < lhs.third ) {
return ( false );
}
// all tied:
return ( false );
}
or
template < typename ForwardIter, typename Pred >
bool forall ( ForwardIter from, ForwardIter to, Pred p ) {
// returns true iff p is not false for all *i in the range [from,to)
while ( from != to ) {
if ( ! p(*from) ) {
return ( false );
}
++ from;
}
return ( true );
}
Best
Kai-Uwe Bux