【C】goto语句使用的两种方式
方式1统一的错误处理在函数中多个地方可能出现错误时用goto跳转到同一个错误处理逻辑避免代码重复。int func() { if (操作1失败) { goto error; } if (操作2失败) { goto error; } // 正常逻辑 return 0; error: // 错误处理如释放资源 return -1; }方式2统一的资源释放避免重复代码确保资源被释放。#include stdlib.h #include stdio.h int func() { int* res1 NULL; // 资源1动态内存 FILE* res2 NULL; // 资源2文件句柄 int ret -1; // 函数返回值默认失败 // 申请资源1 res1 malloc(100); if (res1 NULL) { goto cleanup; // 失败则跳转清理 } // 申请资源2 res2 fopen(data.txt, r); if (res2 NULL) { goto cleanup; // 失败则跳转清理 } // 正常业务逻辑假设执行成功 ret 0; // 标记为成功 cleanup: // 统一资源释放点 // 释放资源2后申请的先释放避免依赖 if (res2 ! NULL) { fclose(res2); } // 释放资源1 if (res1 ! NULL) { free(res1); } return ret; // 返回执行结果 }