gpt4 book ai didi

在 C 中执行多次撤消的简洁方法

转载 作者:太空狗 更新时间:2023-10-29 16:20:13 26 4
gpt4 key购买 nike

有人可能会说一些关于异常的事情......但是在 C 中,还有哪些其他方法可以干净/清楚地执行以下操作并且无需重复那么多代码?

if (Do1()) { printf("Failed 1"); return 1; }
if (Do2()) { Undo1(); printf("Failed 2"); return 2; }
if (Do3()) { Undo2(); Undo1(); printf("Failed 3"); return 3; }
if (Do4()) { Undo3(); Undo2(); Undo1(); printf("Failed 4"); return 4; }
if (Do5()) { Undo4(); Undo3(); Undo2(); Undo1(); printf("Failed 5"); return 5; }
Etc...

这可能是使用 goto 的一种情况。或者可能有多个内部函数...

最佳答案

是的,在这种情况下使用 goto 以避免重复自己是很常见的。

一个例子:

int hello() {
int result;

if (Do1()) { result = 1; goto err_one; }
if (Do2()) { result = 2; goto err_two; }
if (Do3()) { result = 3; goto err_three; }
if (Do4()) { result = 4; goto err_four; }
if (Do5()) { result = 5; goto err_five; }

// Assuming you'd like to return 0 on success.
return 0;

err_five:
Undo4();
err_four:
Undo3();
err_three:
Undo2();
err_two:
Undo1();
err_one:
printf("Failed %i", result);
return result;
}

与往常一样,您可能还希望保持函数较小,并以有意义的方式将操作批处理在一起,以避免出现大量“撤消代码”。

关于在 C 中执行多次撤消的简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53444743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com