C 的 goto语句

等级 5343 次按键

使用 C 中常见的 goto 清理模式:两次分配中任何一次失败,都会跳到同一个 cleanup 标签,释放已分配的内存。这里两次都成功,因此打印 Allocation successful、Processing data... 和 Cleanup complete。

C 代码

// 两个指针都初始化为 NULL,清理代码才能判断哪些已经分配
1int *data = NULL;
2int *buffer = NULL;
3
// 第一次分配:10 个 int
4data = (int *)malloc(sizeof(int) * 10);
// 失败时直接跳到 cleanup
5if (data == NULL) goto cleanup;
6
// 第二次分配:20 个 int
7buffer = (int *)malloc(sizeof(int) * 20);
// 失败时,cleanup 仍需释放已分配的 data
8if (buffer == NULL) goto cleanup;
9
// 只有两次分配都成功时才会执行到这里
10printf("Allocation successful\n");
11printf("Processing data...\n");
12
// 唯一的出口:正常流程也会顺序执行到这个标签
13cleanup:
// 仅当 buffer 已分配时才释放(free(NULL) 其实也无害)
14 if (buffer) free(buffer);
// 对 data 做同样的检查
15 if (data) free(data);
// 打印“Cleanup complete”
16 printf("Cleanup complete\n");

运行结果

Allocation successful
Processing data...
Cleanup complete
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C 代码中需要输入的符号及其出现次数。

  • (× 15
  • )× 15
  • ;× 11
  • =× 8
  • "× 6
  • *× 6
  • .× 3
  • \× 3
  • :× 1

C 等级 5 的更多代码示例

← 返回 C 打字练习