在这种情况下使用goto是不是很糟糕?

时间:2015-06-04 18:04:20

标签: c++ calculator

我一直在使用基于控制台的计算器应用程序,我想使用2个功能以使其看起来更干净(我不想主要有太多行),所以我决定使用goto从main跳到我的陪衬函数,然后另一个转到跳回main的开头。我只是想知道这样做是否不安全。谢谢:))

void foileq()
{
    int a, b, c, d;
    printf("Enter the 4 numbers\n");
    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 number\n");
                cin >> a;
                printf("Enter another number\n");
                cin >> b;
                if (strcmp(type.c_str(), "add") == 0)
                    printf("%.2f\n", a + b);
                else if (strcmp(type.c_str(), "subtract") == 0)
                    printf("%.2f\n", a - b);
                else if (strcmp(type.c_str(), "multiply") == 0)
                    printf("%.2f\n", a * b);
                else if (strcmp(type.c_str(), "divide") == 0)
                    printf("%.2f\n", a / b);
                else if (strcmp(type.c_str(), "power") == 0)
                    printf("%.2f\n", pow(a, b));
            }
        }
    }
FOIL:
    foileq();
    goto BEGIN;
}

3 个答案:

答案 0 :(得分:3)

如果您拨打foileq();而不是goto FOIL;,则行为会相同。在这种情况下,使用goto不会使事情更具可读性。在极少数情况下,goto会使代码更好,而这不是其中之一。

此外,由于前面有continue,因此不需要您当前编写的goto

答案 1 :(得分:0)

  

GOTO看似普遍的革命很大程度上归功于Edsger Dijkstra的信“Go To Statement Considered Harmful”。

(来源:while(1) .. break instead of goto

当键入==“foil”

时,使用while循环退出
while( type != "foil" )

然后将else更改为if(type!=“foil”)以防止输入为箔时运行。

答案 2 :(得分:0)

  

&#34;在这种情况下使用goto是不是很糟糕?&#34;

在任何情况下使用goto几乎总是被视为 错误 。如果你使用它,不要向后跳,而只能向前跳。

以下内容(使用单个标签)可能没问题:

 int foo() {
     while(loop_condition_ok) {
         if(inner_operation_fails()) {
             goto hell;
         }
     }
     return 0;

 hell:
     return -1;
 }