有些人会反对这一点,但我认为在这些情况下,plain oldgoto
是一种非常干净易读的做事方式,因为它强调了“正常”控制路径的线性:
int main(int arg, char *argv[])
{
int choice;
choose_shape:
printf("Choose a shape from the following:\n"
" 1.Sphere\n 2.Cone\n 3.Cylinder\n");
scanf("%d", &choice);
if (choice < 1 || choice > 3) {
printf("Invalid selection, please choose again.\n");
goto choose_shape;
}
printf("Enter the radius, r:\n");
...
}
是的,人们抱怨过,goto
所以让我再证明一下。
这是一个更复杂的版本,允许您按字母选择形状:
char c;
shape_t shape;
choose_shape:
printf("Choose a shape: [s]phere, [c]one, c[y]linder:\n");
scanf("%c", &c);
switch (c) {
cases 's':
shape = SHAPE_SPHERE;
break;
case 'c':
shape = SHAPE_CONE;
break;
case 'y':
shape = SHAPE_CYLINDER;
break;
default:
printf("Not a valid shape: %c\n", c);
goto choose_shape;
}
这是带有goto
. 请注意,这引入了另一个变量 ,flag
其唯一目的是摆脱该goto
语句。由于该语句,您不能简单地break
在此处使用(这是一个未标记goto
的开头) 。switch
由于额外的状态,我认为这更难阅读。它长了五行。
char c;
shape_t shape;
int flag;
for (flag = 0; !flag; ) {
printf("Choose a shape: [s]phere, [c]one, c[y]linder:\n");
scanf("%c", &c);
switch (c) {
cases 's':
shape = SHAPE_SPHERE;
flag = 1;
break;
case 'c':
shape = SHAPE_CONE;
flag = 1;
break;
case 'y':
shape = SHAPE_CYLINDER;
flag = 1;
break;
default:
printf("Not a valid shape: %c\n", c);
break;
}
}