I've read an article about the "Named Loop Idiom" in C++ : http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Loop
This idiom allows us to write things like that :
named(outer)
for(int i = 0 ; i < rows ; ++i) {
named(inner)
for(int j = 0 ; j < cols ; ++j) {
if(some_condition)
break(outer); // exit the 'outer' loop
}
}
Such constructs already exists as core feature in many languages, like Java for instance.
According to the article, it can be implemented in C++ by defining two evil macros :
#define named(blockname) goto blockname; \
blockname##_skip: if (0) \
blockname:
#define break(blockname) goto blockname##_skip;
I know that many people would like to banish the use of goto
. I personally found it helpful in very rare cases, especially when I wanted to break
a bunch of nested loops. This idiom appears to me as a cleaner solution for that, but is it ok to use it in real code ?
On the discussion page of the article, one can read :
"Do not do this. You'll end up in hell"
So my questions are : What are the drawbacks of using the named loop idiom ? Is it dangerous ? If yes, why ?
Bonus question : is it possible to implement named continue
similarly ? (I think it's not possible using the named(...) for(...;...;...) {}
syntax, but who knows ?)
EDIT : I agree with you, redefining a keyword is nasty. What about using #define breakLoop()
instead?