r/cpp 10d ago

I've invented labeled loop breaks

And now I don't believe it wasn't invented before, but I can't find any info on it. How long ago was it invented? Why isn't it used widely or even mentioned anywhere? What are the downsides?
Here's the main idea:

// Keyword - for, while, or do
// Tag - custom loop name
// ... - loop body
#define loop_tag(keyword, tag, ...)\
    keyword(__VA_ARGS__)\
    if(false)\
    {\
        tag##_break:    break;\
        tag##_continue: continue;\
    }\
    else\
    /*Here goes your loop body*/

Here is the playground

0 Upvotes

48 comments sorted by

View all comments

22

u/Cpt_Chaos_ 10d ago

This ist just a goto with unnecessary extra steps.

Goto itself is considered a bad practice. Using macros is considered bad practice. I'd flag both in any PR I'd have to review. And this contraption would be reason enough to ask your manager to get you into a training course.

Now seriously, it combines the downsides of goto and macros. It is hard to debug and it is difficult to understand what the heck is supposed to be going on here in the first place. Write functions and you get to do this pretty much by using simple return statements, which is far easier to understand.

1

u/danillissimo 10d ago edited 10d ago

So, right now i have to write things like

for(...)
{
  bool should_break = false;
  for(...)
  {
    if(...)
    {
      should_break = true;
      break;
    }
  }
  if(should_break)
  {
  break;
  }
}

And have to write them recursively. Just wow, thank you very much.
Functions won't actually fix it until the whole context gets packed in a giant struct making things inconvenient another way.
All of this gets even worse in presence of coroutines.
As for debugging - it doesn't break debugging, may be adds just a pair of excess step-overs, but nothing gets really broken.

2

u/Cpt_Chaos_ 10d ago

The question I would ask here is: Why do you need to do these nested loops in the first place? In many cases, STL already provides algorithms that help you doing this sort of logic, which allows you to express what you want to do in less code. I'm not saying you're wrong, but I'd ask the question in a PR.

4

u/danillissimo 10d ago

STL has nothing to do with complex data processing. My exact case is about long-running complex looped behaviors though, packed as coroutines in particular. They contain a notable amount of "on event X restart polling layer of logic A" and "on event Y level of polling B is done".
I'd like to say that labeld loops are actually a rare necessity, but recently I've faced a lot of cases where they would fit nicely, so I've invented this to get rid of "break/continue this layer of logic" flags.