Search code examples
c++flow-control

c++ unless wrapper construct for flow control


I have a program part that works similar to the following:

X->updateA();
X->updateB();
X->updateC();
X->updateD();

Each function is supposed to return an integer indicating whether it ran successfully or not, say int ret_val=0 if successful and int ret_val=1 if not.

I am wondering if there exists any wrapper construct that processes each function consecutively as long as ret_val == 0. In my case it shall also call X->updateD(); regardless of the value of ret_val.

Right now I have:

int ret_val = 0;
ret_val = X->updateA();
if (ret_val == 0) ret_val = X->updateB();
if (ret_val == 0) ret_val = X->updateC();
X->updateD();

Which I think is not really readable. What I'd prefer is something similar to the while-loop, although it would have to check for the condition after each function call. Something along the lines of this:

int ret_val = 0;
unless(ret_val != 0)
{
  ret_val = X->updateA();
  ret_val = X->updateB();
  ret_val = X->updateC();
}
X->updateD();

Is there any such construct?


Solution

  • You should use exceptions. Effectively they are an external control flow mechanism which means that you do not have to litter your regular code with error handling and manually propagate every error and check for errors on every call. With exceptions, your original code is perfectly valid as-is and the compiler generates code to check for errors and propagate them to the caller if one occurred.