In C a typical way to simplify error checking and avoid deep nested if
is:
do
{
if (condition1) break;
/* 1. do something... */
if (condition2) break;
/* 2. do something else... */
if (condition3) break;
/* 3. do something else... */
} while(0);
/* Cleanup */
There are various opinion on this "idiom" (e.g. take a look at Do you consider this technique “BAD”?).
Possibly you should add a comment on the do
to make it clear to anyone what's happening.
You can often rewrite the code using a helper function and change the fake do-loop into:
void func(X *x, Y *y)
{
if (condition1) return;
/* 1. do something... */
if (condition2) return;
/* 2. do something else... */
if (condition3) return;
/* 3. do something else... */
}
/* ... */
X x;
Y y;
func(&x, &y);
/* Cleanup */
and it won't be considered a "bad practice" since it's more expected.
If you haven't the intermediate steps (1.
and 2.
) this is probably enough:
int stop = condition1 || condition2 || condition3;
if (!stop)
{
/* ... */
}
/* Cleanup */