使用什么而不是Goto语句?

Bla*_*lls 2 c++ if-statement goto

我想知道我应该使用什么而不是goto语句?

我应该使用嵌套的if/while/do-while语句吗?

他们说使用goto会创建'意大利面条代码',但是如果有人正在编写一个大型控制台应用程序,并且他们在if语句之后使用if语句来试图控制流量,那么这会变得一团糟吗?

我问很多人都问为什么goto语句不好,但不知道要用什么来代替它.我相信很多初学者都可以做到这一点.

这适用于C++.

M2t*_*2tM 7

使用函数,循环和条件语句会好得多.使用break并根据需要继续.

我几乎可以保证你使用goto的任何情况都有更好的选择.有一个值得注意的例外:多级休息.

while(1){
    while(1){
        goto breakOut;
    }
    //more code here?
}
breakOut:
Run Code Online (Sandbox Code Playgroud)

在这个(相对)罕见的情况下,可以使用goto代替典型的"中断",以明确我们实际上已经脱离了嵌套循环.另一种方法是使用"完成"变量:

while(!done){
    while(!done){
        done = true;
        break;
    }
    if(done){break;}
    //More code here?  If so, the above line is important!
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,当您在外部循环中进行额外处理时,done变量更加冗长,因此goto是一种更清晰的自由方式!

但是,在99%的情况下,你真的,真的,不想开始编写一堆goto语句.真的想通过每一个.

有了函数,上面也可以写成:

bool innerLoop(){
    while(1){
        return false;
    }
    return true;
}

...
while(innerLoop()){ //can only be written this way if the inner loop is the first thing that should run.
    //More code here?
}
...
Run Code Online (Sandbox Code Playgroud)

如果在外部循环中存在大量依赖性,有时以这种方式打破内部循环可能会很混乱.但它仍然是使用return语句而不是goto或break来尽早破解代码的可行方法.