在这种情况下用goto不好吗?
Is it bad to use goto in this situation?
我一直在制作一个基于控制台的计算器应用程序,为了让它看起来更干净,我想使用2个函数(我不想让main有太多行),所以我决定使用goto从main跳转到我的foil函数,然后使用另一个goto跳转到main的开始。我只是想知道这样做是否不安全。谢谢:)
void foileq()
{
int a, b, c, d;
printf("Enter the 4 numbersn");
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cout << a * c << " " << a * d << " " << b * c << " " << b * d << endl;
}
int main()
{
float a, b;
string type = "";
BEGIN:
{
while (1)
{
printf("Add,subtract,multiply,divide,foil,power?n");
cin >> type;
if (type == "foil")
{
goto FOIL;
continue;
}
else
{
printf("Enter A numbern");
cin >> a;
printf("Enter another numbern");
cin >> b;
if (strcmp(type.c_str(), "add") == 0)
printf("%.2fn", a + b);
else if (strcmp(type.c_str(), "subtract") == 0)
printf("%.2fn", a - b);
else if (strcmp(type.c_str(), "multiply") == 0)
printf("%.2fn", a * b);
else if (strcmp(type.c_str(), "divide") == 0)
printf("%.2fn", a / b);
else if (strcmp(type.c_str(), "power") == 0)
printf("%.2fn", pow(a, b));
}
}
}
FOIL:
foileq();
goto BEGIN;
}
如果调用foileq();
而不是goto FOIL;
,其行为将是相同的。在这种情况下,使用goto并不能使内容更具可读性。很少有goto使代码变得更好的情况,这不是其中之一。
continue
是不需要的,因为goto
就在它前面。
"在这种情况下使用
goto
不好吗?"
几乎总是认为在任何情况下使用goto
都是不好的。如果你使用它,不要向后跳,只能向前跳。
下面的内容(使用一个标签)可能是可以的:
int foo() {
while(loop_condition_ok) {
if(inner_operation_fails()) {
goto hell;
}
}
return 0;
hell:
return -1;
}
看似普遍的GOTO革命很大程度上是由于Edsger Dijkstra的信"Go to声明被认为是有害的"。
(来源:while(1)…Break代替goto)
当type == "foil"
使用while循环退出while( type != "foil" )
然后将else更改为if(type != "foil"),以防止在输入为foil时运行。
相关文章:
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 在这种情况下,java对象是否可以调用本机函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 在这种情况下,我真的复制了字节还是复制了字符?
- 为什么在这种情况下,bool 类型的输出等于 0?
- 在这种情况下,如何传递成员函数而不是函数?
- 为什么在这种情况下递增阵列名称有效?
- 在这种情况下我应该使用哪种设计模式
- 为什么在这种情况下我需要 .template
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 我是否访问了已释放的内存,或者在这种情况下DrMemory报告不正确?
- 在这种情况下,"typename..."意味着什么?
- 为什么在这种情况下 x = 44?
- 在这种情况下是私有的吗?试图使操作员<<过载
- 在这种情况下,如何防止C++输出/控制台窗体关闭
- 为什么 lambda nullptr 取消引用在这种情况下有效?
- 为什么在这种情况下,前向声明不起作用?
- 在这种情况下,我应该避免"goto"吗?
- 在这种情况下我可以使用goto吗
- 在这种情况下用goto不好吗?