适当使用IF Goto循环的方法

Proper method for using if goto loop

本文关键字:循环 方法 Goto IF      更新时间:2023-10-16

我想问一下这是C 中的goto loop:

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

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

注意:它使用G 在Linux Mint上成功编译。

可以说,没有适当的使用goto。改用结构化循环:

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

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

我的建议是忘记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时,但两个程序不是等效的。

考虑到您的孔隙中不使用变量A且应删除其声明。

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