I read that both multiple returns and multiple goto statements are bad programming practice. I have a function which can detect some 8 types of errors. In case of error, should i return error code or should i use goto statment to go to end of function and return from there.
Whenever memory freeing is required before returning from function, i thought it would be better to have a goto end and free the memory at the end of the function(so that only one free is enough in function)
However, In my function, memory is not allocated.
In this case which one is preferable ? Multiple returns or multiple goto statements ?
Or can we avoid both ?
EDIT: Some way to avoid both is, pass parameter to function which can store errorType. Samething can be checked inside function before proceeding further. But this too makes the code ugly.
If you look at how goto is used in C code, such as the Linux kernel, it is used to do resource cleanup prior to returning from a function. Multiple labels are used to deallocate resources in the reverse order of acquisition, with earlier parts of the code jumping to later goto labels.
In C++, instead you should use RAII to manage your resources. Then you can use multiple return statements and any needed cleanup will happen automatically.
However if you are detecting many different types of errors, your functions/methods may be exhibiting low cohesion and you may want to consider splitting your functions/methods up into smaller units. This can make error handling more difficult as you may now have more complex return paths, so to avoid this cumbersome error handling, look to use exceptions instead of error return values. This will dovetail nicely with RAII to clean up resources automatically.