Thursday, 2 July 2009

How Not To Use Goto In C Init Functions

There is the idea that Goto is useful in some complex init functions to make the code simpler. Such as:

if (OK != doSomething()) goto cleanup;
if (OK != doSomethingElse()) goto cleanup;

There could dozens of functions that need to be called except if something goes wrong in which case the rest of the init functions should not be called.

This is thought to be better because the normal style of if's makes the code much more complex. But there is a better way of doing initialization code like this that doesn't make the code any longer:

error = (!error) && doSomething();
error = (!error) && doSomethingElse();

Or, if you want to know which function failed you can either have different return codes for each function or do this:

error = (!error) && (doSomething() << SHIFT_DOSOMETHING);
error = (!error) && (doSomething Else() << SHIFT_DOSOMETHINGELSE);

I would prefer each function returning it's own error code because the latter style is not quite as easy to read and relies on functions returning 1 on error (the first version works with any return values).

This is a pretty easy way of solving the same problem and does not add any cyclomatic complexity and keeps the code short, without any extra constructs.

No comments:

Post a Comment