在c中多久使用一次goto语句? [重复]

问题描述 投票:0回答:1

我是c的初学者。我了解到,可以使用goto语句一次摆脱所有嵌套循环。我还了解到它在C语言中并不是那么受欢迎。但是,我经常使用它,因为我认为它有很大帮助,有时,它比常见的替代方法容易得多。这是一个小程序,其中我使用goto语句来更正用户的错误,而不是使用循环。因此,我的问题是:我真的应该停止使用它吗?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    /*A program to store a number in 4 bits only !*/
    printf("Enter x then z :\n");
    int x, y;
    Start:
    scanf("%d %d", &x, &y);
    if((x > 15) || (y > 15) || (x < 0) || (y < 0))
    {
        printf("Wrong numbers! : 0<= x,y <=15\n");
        printf("Enter the numbers again : \n");
        goto Start;
    }
    char z;
    x<<= 4;
    z = x + y;
    printf("z = %d", z);
    return 0;
}
c goto
1个回答
1
投票

[仅当使用替代方法会使代码更丑陋时才应使用goto-或在某些极端情况下,效果更差

在您的情况下,您的代码可以写为

for (;;) {
    scanf("%d %d", &x, &y);
    if (x >= 0 && x <= 15 && y >= 0 && y <= 15)
        break;
    printf("Wrong numbers! : 0<= x,y <=15\n");
    printf("Enter the numbers again : \n");
}

没有goto,它将是[[也更加清晰,因为表达式现在定义了可接受的值,而不是不可接受的。

© www.soinside.com 2019 - 2024. All rights reserved.