On 15/06/2020 23:44, Frederick Gotham wrote:
> [I have multi-posted this to comp.lang.c and comp.lang.c++]
>
> Have you ever seen code written as follows?
>
> if ( cond1 )
> {
> if ( cond2 )
> {
> if ( cond3 )
> {
> if ( cond4 )
> {
> DoSomething();
> }
> }
> }
> }
How about :
if (cond1 && cond2 && cond3 && cond4) {
DoSomething();
}
>
>
> Well some people think that the above is very poorly written code, and they prefer it like this:
>
>
> if ( !cond1 ) return;
>
> if ( !cond2 ) return;
>
> if ( !cond3 ) return;
>
> if ( !cond4 ) return;
>
> Do Something();
>
That's good for some kind of tests. In particular, tests on the
parameters of a function followed by early exits are a popular style.
(Not everyone likes it - some people feel functions should only ever
have one exit.)
There is no single "best" method - it will depend on the code as well as
any style preferences or requirements for the project and team.
>
> If you can't simply return from the function, and instead want to skip over a section of code, you could use 'goto':
>
>
> if ( !cond1 ) goto Label_At_End;
>
> if ( !cond2 ) goto Label_At_End;
>
> if ( !cond3 ) goto Label_At_End;
>
> if ( !cond4 ) goto Label_At_End;
>
> Do Something();
>
> Label_At_End:
> ;
>
That's also a common idiom. It's not one I like - I don't find use for
gotos in my own code. But some people do.
>
> Some programmers and some firms are very much against the use of 'goto'. In order to avoid using 'goto' today, I instead used a switch statement like this:
>
> switch (true)
> {
> default:;
>
> if ( !cond1 ) break;
>
> if ( !cond2 ) break;
>
> if ( !cond3 ) break;
>
> if ( !cond4 ) break;
>
> Do Something();
> }
>
That would be a code review fail right away - it's an unnecessarily ugly
hack and an abuse of switch. Your "do {} while (false);" is much less
bad (omitting the "default:").
>
> Another alternative would have been to use a 'do' loop as follows:
>
>
> do
> {
> default:;
>
> if ( !cond1 ) break;
>
> if ( !cond2 ) break;
>
> if ( !cond3 ) break;
>
> if ( !cond4 ) break;
>
> Do Something();
> } while (false);
>
>
> Does anyone else use fake switches and fake loops like this just to exploit the 'break' keyword?
>
I've never felt the need.