这是C的衍生物,所以请不要生气,因为它看起来不正确.在这个实现中确实是正确的.
我有这个代码:
func() {
if (handler_1()) goto good;
if (handler_2()) goto good;
if (handler_3()) goto good;
print("BAD");
goto done;
good:
print("GOOD");
goto done;
done:
print("DONE");
// do some common stuff
}
Run Code Online (Sandbox Code Playgroud)
我对gotos和标签不是特别满意,所以我尝试使用do-while,但仍有一个GOTO.
func() {
do {
if (handler_1()) break;
if (handler_2()) break;
if (handler_3()) break;
print("BAD");
goto done;
} while(false);
print("GOOD");
done:
print("DONE");
// do some common stuff
}
Run Code Online (Sandbox Code Playgroud)
注意 - 该语言不使用短路评估:
handler_1() || handler_2() || handler_3()
Run Code Online (Sandbox Code Playgroud)
在检查返回值之前,将始终执行所有三个处理程序.我不要那个.
可用结构:SWITCH,GOTO,LABEL,FOR,WHILE,DO-WHILE,IF_ELSEIF_ELSE.也可以制作局部变量.
如何在不使用GOTO的情况下重写此代码的任何想法?
我建议使用与你在linux内核中经常看到的类似的语法.
func() {
if (!handler_1())
goto fail;
if (!handler_2())
goto fail;
if (!handler_3())
goto fail;
print("success");
return 0;
fail:
print("failure");
return -1;
}
Run Code Online (Sandbox Code Playgroud)
这是一个变种
func() {
int good = 0;
if (handler_1())
good = 1;
else if (handler_2())
good = 1;
else if (handler_3())
good = 1
if (good) {
print("GOOD");
} else {
print("BAD");
}
print("DONE");
// do some common stuff
}
Run Code Online (Sandbox Code Playgroud)