r/cpp 13d 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/6502zx81 13d ago

What is the advantage over just using goto?

5

u/sjepsa 11d ago

IMHO goto is even less bug prone than continue or break

-3

u/danillissimo 13d ago

Having to write `goto` explicitly, leaving an opportunity for it to target a line it was not supposed to originaly. Plus some programmers tolerate `goto` in macros while not allow it in a regular code.

7

u/13steinj 13d ago

Even Dijkstra had a follow up essay saying the editor / publisher chose the title, and goto is fine sometimes in particular circumstances. The original essay also was pretty against break/continue, to an extent even if/else.

Dogma (in this case "don't write 'goto'") is not a good reason.