适当使用IF Goto循环的方法
Proper method for using if goto loop
我想问一下这是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 中的保留关键字。
相关文章:
- 方法内部但循环仍得到预期的不合格id错误C++
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何在C++中循环访问未知对象方法?
- EnQueue 方法在循环队列中未正确返回C++?
- C++模板方法中的循环依赖关系
- 为什么这种方法会进入无限循环?
- 编写按初始值循环的循环的更好方法是什么
- 循环遍历标准的正确方法::array<char*, N>
- 类方法 - 数据结构中 For 循环的运行时错误
- 循环依赖,在继承类的情况下使用覆盖方法
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 是否可以在基于范围的 for 循环中使用模板化的开始/结束方法
- 还有其他方法可以为乘法表编写循环以获取运行时值吗?
- 如何避免模板方法的循环依赖
- 使用虚拟变量对 std::vector 内部循环进行切片的最佳方法
- 有什么方法可以在 c++ 中组织"cycling"(循环)数字?
- C++中的石头剪刀布循环方法
- 对于循环方法调用
- 循环/方法太慢