goto语句在c中的使用频率是多少



我是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 <=15n");
printf("Enter the numbers again : n");
goto Start;
}
char z;
x<<= 4;
z = x + y;
printf("z = %d", z);
return 0;
}

只有当使用替代方案会使代码更丑陋时,或者在某些极端情况下,性能更差时,才应该使用goto

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

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

如果没有goto,它也会更清楚,因为表达式现在定义了可接受的值,而不是不可接受的。

最新更新