All my functions look like this:
short Function()
{
short ret = 0;
ret = FunctionA();
if(ret != 0) return ret;
ret = FunctionB();
if(ret != 0) return ret;
ret = FunctionC();
if(ret != 0) return ret;
return 0;
}
Is there a nicer way to write this? Without having to repeat
if(ret != 0) return ret;
all the time?
If using a short-circuited
||like suggested in the other answer is not an option, you could define a macro for that:Then in your code:
NOTE: You should be very careful when deciding to use macros, but in this case I think it can be a clean way to solve the problem.
It must be mentioned, though, that these statements conceil the fact that the function could return early at every one of them. If you have open resource handles (file descriptors, pointers to
malloced data, …), they will leak. You and everyone working with the code should be aware of this and use appropriate error handling and cleanup routines for more complex cases than this one.