使用if goto循环的正确方法

时间:2015-05-12 17:05:36

标签: c++

我想问一下C ++中这是否是正确的goto循环:

#include <iostream>

int main() {
    int i=0, a=0;
    this:std::cout << i << " is less than 10\n";
    i++;
    if( i<10) goto this;
    return 0;
}

我在非常古老的c ++书中有这个,并且不知道它在当今的C ++中是否正确。

注意:使用g ++在Linux mint上成功编译。

2 个答案:

答案 0 :(得分:7)

可以说,没有正确的方法可以使用goto。改为使用结构化循环:

for (int i = 0; i < 10; ++i) {    
    std::cout << i << " is less than 10\n";
}

如果您坚持使用goto,则必须更改标签的名称。 this是C ++中的关键字,不能用作标识符。

答案 1 :(得分:1)

我的建议是忘记C ++有goto语句而从不使用它。 :)当使用goto语句时,程序会丢失其结构,因此很难读取这些程序。另外一个goto语句通常会在同一个程序中生成另一个goto语句,因为编写结构化代码的规则被破坏了。:)通常很难修改这些程序。

您展示的程序可以通过以下方式重写

#include <iostream>

int main() 
{
    const int N = 10;
    int i = 0;

    do
    { 
       std::cout << i << " is less than " << N << "\n";
    } while ( ++i < N );

    return 0;
}

或以下方式

#include <iostream>

int main() 
{
    const int N = 10;

    for ( int i = 0; i < N; i++ )
    { 
       std::cout << i << " is less than " << N << "\n";
    }

    return 0;
}

虽然一般情况下N可以初始设置为0,但两个程序并不相同。

考虑到你的porgram中没有使用变量a,应该删除它的声明。

使用关键字作为标识符也是一个坏主意。 是C ++中的保留关键字。