Deep nesting vs early returns

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Oct 5 20:29:02 UTC 2018


On Fri, Oct 05, 2018 at 08:00:03PM +0000, Patrick Schluter via Digitalmars-d wrote:
> On Friday, 5 October 2018 at 16:02:49 UTC, Nick Treleaven wrote:
> > On Thursday, 4 October 2018 at 06:43:02 UTC, Gopan wrote:
[...]
> > > while(1)
> > > {
> > > 	...
> > > 	break; //otherwise return would come here.
> > > 	...
> > > 	break;
> > > }
> > > 
> > > return ...;
> > 
> > I think `switch (0) default:` is better, because it's not a loop so
> > the intent is clear - no continue statements somewhere below (so
> > it's also better than `do ... while (0);`). Also you might forget
> > the final break statement with `while` and get an infinite loop.
> > 
> `do ... while (0);` and also the loop above are abominations. They are
> for goto hypocrits, i.e. people who think that a goto when it is not
> named goto but works exactly like a goto is something better (the
> Voldemort goto).

+1.  D (and C/C++) has a 'goto' keyword for a reason.  It's stupid to
try to avoid it like a taboo keyword when it's what the code actually
*means*.  Just because you write it with "more acceptable" constructs
does not change the fact that the code is essentially doing a goto.

Not to mention the fact that modern-day `goto` statements are nowhere
near as powerful (nor as evil) as the original goto, which was
program-wide (and sometimes even more than that, before the days of
protected mode and process isolation :-P), and could jump from anywhere
to literally anywhere else, including the middle of another construct.
Modern-day `goto`s are far tamer, and not overly hard to reason about
provided you don't abuse them for stuff that could be better-written
with other constructs.


> The breaks above and in are GOTOS, no point in obfuscating them. Sorry
> if I'm a little bit inflammatory about these constructs, but I have to
> work with code written by a `do {} while(0)` champion and I can tell
> you, it's the horror when you have to make changes.

I've had to work with code that had multiply-nested #define macros
involving `do {} while(0)`, and have hated every minute of it.


> It was so bad that I finally used  __attribute__((__cleanup__(x))) gcc
> extension to implement something resembling D's scope(exit) so that
> I'm sure that the code doesn't leak like it did before.

Ouch.


T

-- 
"I suspect the best way to deal with procrastination is to put off the procrastination itself until later. I've been meaning to try this, but haven't gotten around to it yet. " -- swr


More information about the Digitalmars-d mailing list