gpt4 book ai didi

c - 管理 if 语句

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

海湾合作委员会 4.4.3 c89

我有一些函数可以初始化一些硬件并返回 true 或 false。如果为假,那么我必须以相反的顺序取消初始化。

但是,我的代码看起来非常不整洁,包含所有 if 语句。

例如,每个函数都可以返回 true 或 false。这是一个样本。如您所见,代码看起来非常凌乱。我只是在寻找有关如何清理它以使其更易于管理并在可能的情况下可扩展的任何建议?

非常感谢任何建议,

if(init_A() == TRUE) {
if(init_B() == TRUE) {
if(init_C() == TRUE) {
if(init_D() == TRUE) {
if(init_E() == TRUE) {
/* ALL STARTED OK */
}
else {
uninit_A();
uninit_B();
uninit_C();
uninit_D();
}
}
else {
uninit_A();
uninit_B();
uninit_C();
}
}
else {
uninit_A();
uninit_B();
}
}
else {
/* Failed to initialize B */
uninit_B();
}
}
else {
/* Failed to start */
}

最佳答案

if(init_A() != TRUE) {
goto EndA;
}
if(init_B() != TRUE) {
goto EndB;
}
if(init_C() != TRUE) {
goto EndC;
}
if(init_D() != TRUE) {
goto EndD;
}
if(init_E() != TRUE) {
goto EndE;
}
...
return;
EndE: uninitD();
EndD: uninitC();
EndC: uninitB();
EndB: uninitA();
EndA: return;

关于c - 管理 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3706893/

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