在这种情况下用goto不好吗?

Is it bad to use goto in this situation?

本文关键字:goto 这种情况下      更新时间:2023-10-16

我一直在制作一个基于控制台的计算器应用程序,为了让它看起来更干净,我想使用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时运行。