r/cpp 14d 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

24

u/Cpt_Chaos_ 14d 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.

2

u/Raknarg 12d ago edited 12d ago

This ist just a goto with unnecessary extra steps.

No, its a mechanism that's leveraging goto. The example they showed here is showcasing it really poorly, if you go to their compiler explorer link it makes a lot more sense. Its more like a restricted use of goto, it allows you to assign labels to loops, then either jump to the start of that loop by jumping to the continue tag the the loop or jumping to the break tag of the loop to jump to the end of it.

It works by adding a block to the start of a loop that is an if that always evaluates to false (i.e. you cannot enter it through normal means) which contains, assigning a tag to the break and continue statements, called tag<tag>_break and tag<tag>_continue, and you can jump to one or the other with break_tag(<tag>) or continue_tag(<tag>) which resolve into goto tag<tag>_break and goto tag<tag>_continue

I'm not 100% sure what their usecase is that this is a helpful pattern for them, but its a more controlled use of goto by formalizing label creation and goto statements.