我使用错误代码作为返回值。但是每次调用函数时,我都会使用 if-else 来检查返回值是否是一个好的结果。 例如,
int v1,v2,v3,v4;
v1 = func1();
if(v1 != OK){
// do somethings
}
else{
v2 = func2();
if(v2!=OK){
// do somethings
}
else{
v3 = func3();
if(v3!=OK){
// do somethings
}
else{
v4 = func4();
if(v4!=OK){
// do somethings
}
else{
.....
}
}
}
}
最佳答案
如果原型(prototype)相同,您可以使用循环:
using f_ptr = int (*)();
using error_f_ptr = void (*)();
std::pair<f_ptr, error_f_ptr> funcs[] = {
{&func1, &err1},
{&func2, &err2},
{&func3, &err3},
{&func4, &err4}
};
for (const auto& p : funcs) {
const int v = p.first();
if (v != OK) {
p.second();
return FAIL;
}
}
return OK;
关于c++ - 如何避免使用多个if-else检查返回值是否为错误码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718579/