命名循环习语:危险? [英] The named loop idiom : dangerous?

查看:233
本文介绍了命名循环习语:危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中阅读了一篇关于命名循环语言的文章: http:// en .wikibooks.org / wiki / More_C%2B%2B_Idioms / Named_Loop

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 

   }
}

这样的结构已经作为核心特性在许多语言中存在,例如Java。

Such constructs already exists as core feature in many languages, like Java for instance.

根据文章,它可以通过定义两个邪恶的宏来实现: / p>

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;

我知道很多人都想取消使用 goto 。我个人发现它在非常罕见的情况下有用,特别是当我想要 break 一堆嵌套循环时。这个习语在我看来是一个更清洁的解决方案,但它是否可以使用它在真正的代码?

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"

所以我的问题是:使用命名循环惯用法有什么缺点?危险吗 ?如果是,为什么?

奖金问题:是否可以实现 continue 类似? (我认为不可能使用 named(...)for(...; ...; ...){} 语法,但谁知道?

Bonus question : is it possible to implement named continue similarly ? (I think it's not possible using the named(...) for(...;...;...) {} syntax, but who knows ?)

编辑:我同意你的意见,重新定义一个关键字是令人讨厌的。那么如何使用 #define breakLoop()

EDIT : I agree with you, redefining a keyword is nasty. What about using #define breakLoop() instead?

推荐答案

在注释中,#defining break 有问题。让我们假设你使用别的东西。

As covered in the comments, #defining break is problematic. Let's assume you use something else.

我仍然认为这是危险的。这是一个非常不寻常的成语(对C ++程序员),所以他们不太可能理解,因此他们可能会做出突破性的改变。考虑到没有什么令人惊讶的,因此不太危险的方法来完成同样的事情,我建议反对它。

I'd still argue that this is dangerous. It's an extremely unusual idiom (to C++ programmers), so they're less likely to understand, and thus they might make breaking changes. Given that there are less-surprising--and therefore less-dangerous--ways to accomplish the same thing, I would advise against it.

考虑把循环放在函数或lambda。然后你可以 return 打破外层循环。作为一个好处,您可以返回关于提前退出的信息,这对于外部代码可能是有用的。

Consider putting the loops in a function or a lambda. Then you can return to break out of the outer loop. As a benefit, you can return information about the premature exit, which may be useful to the outer code.

这篇关于命名循环习语:危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆