goto
2026/7/13小于 1 分钟
goto
虽然goto被"嫌弃",但在嵌入式中有合理使用场景:
资源清理(Linux内核风格):
int init_device(void) {
if (alloc_A()) goto fail_a;
if (alloc_B()) goto fail_b;
if (alloc_C()) goto fail_c;
return 0;
fail_c: free_B();
fail_b: free_A();
fail_a: return -1;
}优势:
- 清理逻辑集中,不用层层嵌套if-else
- 不会遗漏释放
- Linux内核编码规范推荐这种用法
规则:只允许向前跳转到清理代码,不要向后跳转形成循环。

