The project is in C, so I apologise to all the C++ purists on the board, who might want to suggest more elegant C++ solutions. I believe I'm not completely out of line posting here though, since C is a "subset" of C++, and the real problem is less about language features and more about logic, which exists in abundance on this forum (I'm a champion at sucking up ;-)).
I've got some code that has fallen foul of a coding standards review. The alleged reason being that I've used an assignment in an if statement.
Personally, I think they've missed the point, but I still have to change the code. I'm looking for suggestions on how to implement a clean alternative.
Other rules that restrict the solution are that I'm only allowed one point of exit from the function, and I can't use break or goto (not that I'd want to in this situation).
The code in question looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
int status = -1;
...
if ((status = functionReturningInt()) != 0)
{
// log the errors
// clean-up all work done so far
...
}
else if ((status = anotherFunctionReturningInt()) != 0)
{
// log the errors
// clean-up all work done so far
...
}
else if ((status = yetAnotherFunctionReturningInt()) != 0
{
// log the errors
// clean-up all work done so far
...
}
...
// many more if-else
else
{
// We got here without any errors
// log successful status, etc.
}
// log errors,
// clean up everything
return status;
|
You see my problem, I don't want to continue if any of the function calls fail, so I use the if-else to make sure. Unfortunately, it's quite a long chain, and if I try and nest the if-else blocks, I break another rule about the level of nesting permitted. I imagine this problem must pop up a lot, so I'm convinced there's a simple and obvious solution I'm missing.
The cursory review assumed (I think) that I was doing something like
1 2 3 4
|
if (x = function())
{
...
}
|
Which, I agree is dangerous, but is not what I did.
All solutions I've thought of have appeared too messy or complicated for such a simple task. All suggestions are welcome, many thanks.