goto
语句已经在多次 SO 讨论中进行了详细的研究(参见 this 和 that ),我当然不想再次引发这些激烈的争论。
相反,我想重点关注 goto
的单个用例,并讨论其值(value)和可能的替代方案。
考虑以下代码片段,它在(至少是我自己的)FSM 中很常见:
while (state = next_state()) {
switch (state) {
case foo:
/* handle foo, and finally: */
if (error) goto cleanup;
break;
case bar:
/* handle bar, and finally: */
if (error) goto cleanup;
break;
/* ...other cases... */
}
}
return ok;
cleanup:
/* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
return error;
仅仅为了保存goto
而在单独的函数中交换清理内容似乎很尴尬。另一方面,我们一直反对尽可能使用 goto
。
我的问题:我的代码示例被认为是好的风格吗?
如果没有,是否有可行的替代方案?
请遵守上述goto
的具体用法。我不想深入讨论有关 goto
的一般用法。
最佳答案
您对goto
的使用是可以的。它不会破坏使用 goto 的 2 种好方法。
goto
必须在源代码中向下(几行)- 最里面的
goto标签
block 必须包含goto
语句
关于c - 在函数结束时跳转到清理时 GOTO 是否被认为是无害的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5702163/