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

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

问题描述

我读过有关命名循环成语在C ++中的一篇文章:<一href=\"http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Loop\">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.

根据文章通过定义二恶宏,可以在C ++实现的:

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;

我知道很多人想驱逐使用转到的。我个人发现在极少数情况很有帮助,特别是当我想要一堆嵌套循环。这个成语在我看来,作为一个清洁的解决方案,但它是确定在现实code使用它?

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"

所以我的问题是:什么是使用指定的循环成语的弊端?危险吗 ?如果是,为什么?

奖金的问题:是有可能实现名为继续相似? (我认为它使用是不可能的的(......指定(...); ...; ...){} 语法,但谁知道)

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 是有问题的。让我们假设你用别的东西。

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。然后,你可以收益打出来的外循环。作为一个好处,你可以返回有关premature退出,这可能是外code有用的信息。

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天全站免登陆