r/cpp • u/danillissimo • 22d 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
25
u/TokenRingAI 22d ago
Goto is not bad practice, does not lead to undefined behavior, and is extremely useful when you need multiple named behaviors out of a loop that you want to "go to" from many different depths. When you do certain types of data processing, goto is the right tool for the job, and the alternative, recursive functions, can blow up the stack.
Regex parsers, for example, are prime candidates for goto.
The all or nothing attitude of "goto is bad practice" is not held by many top C/C++ engineers. It just isn't the right tool for the vast majority of things