如何避免使用goto并有效打破嵌套循环 [英] How to avoid use of goto and break nested loops efficiently

查看:206
本文介绍了如何避免使用goto并有效打破嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要说的事实是,在C / C ++编程中,使用 goto 被认为是一种不好的做法。

I'd say that it's a fact that using goto is considered a bad practice when it comes to programming in C/C++.

但是,给出以下代码

for (i = 0; i < N; ++i) 
{
    for (j = 0; j < N; j++) 
    {
        for (k = 0; k < N; ++k) 
        {
            ...
            if (condition)
                goto out;
            ...
        }
    }
}
out:
    ...

我想知道如何不使用 goto 有效地实现相同的行为。我的意思是,例如,我们可以在每个循环结束时执行类似的操作,例如检查 condition ,但是AFAIK goto只会生成一条汇编指令,该指令将是 jmp 。因此,这是我能想到的最有效的方法。

I wonder how to achieve the same behavior efficiently not using goto. What i mean is that we could do something like checking condition at the end of every loop, for example, but AFAIK goto will generate just one assembly instruction which will be a jmp. So this is the most efficient way of doing this I can think of.

还有其他被认为是好的做法吗?当我说使用goto被认为是不好的做法时,我错了吗?如果我愿意,这会是使用它的好例子吗?

Is there any other that is considered a good practice? Am I wrong when I say it is considered a bad practice to use goto? If I am, would this be one of those cases where it's good to use it?

谢谢

推荐答案

(imo)最好的非goto版本如下所示:

The (imo) best non-goto version would look something like this:

void calculateStuff()
{
    // Please use better names than this.
    doSomeStuff();
    doLoopyStuff();
    doMoreStuff();
}

void doLoopyStuff()
{
    for (i = 0; i < N; ++i) 
    {
        for (j = 0; j < N; j++) 
        {
            for (k = 0; k < N; ++k) 
            {
                /* do something */

                if (/*condition*/)
                    return; // Intuitive control flow without goto

                /* do something */
            }
        }
    }
}

将其拆分也是一个好主意,因为它可以帮助您使函数简短,代码可读(如果您对函数的命名比我更好,确实如此,依赖性较低。

Splitting this up is also probably a good idea because it helps you keep your functions short, your code readable (if you name the functions better than I did) and dependencies low.

这篇关于如何避免使用goto并有效打破嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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