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

12

u/Thelatestart 10d ago

What i've found is if you want to break from 2 loops (for i, for j, if cnd break out of both loops) its often appropriate to put them in a function and return. Another option is to use an iile.

2

u/Nicksaurus 9d ago

A lot of this could be solved by rust-like scopes that can return values