Red Squirrel
[H]F Junkie
- Joined
- Nov 29, 2009
- Messages
- 9,211
Say I have this code in a function:
There are multiple return paths, but just exiting like that means I may not be freeing up memory or finishing anything that may need to be done, depending on what the function does. What is the best way to deal with this? I've seen simply making sure to deallocate stuff at each return point, but that seems error prone to me.
Is the better way to simply have lot of nested ifs and have a single return path? Ex instead of just having the if(error) you then have an else { } and put the rest of the code in there. Is that considered better practice?
I've actually seen people use goto in situations like this, but I don't think that's considered a practical thing either.
Code:
int Function()
{
int error = SomeInitFunction();
if(error)
{
return error;
}
//allocate some memory or something
error = SomeOtherFunction();
if(error)
{
return error;
}
error = SomeOtherFunction2();
if(error)
{
return error;
}
//(etc)
//finalize everything, deallocate memory etc
return 0;
}
There are multiple return paths, but just exiting like that means I may not be freeing up memory or finishing anything that may need to be done, depending on what the function does. What is the best way to deal with this? I've seen simply making sure to deallocate stuff at each return point, but that seems error prone to me.
Is the better way to simply have lot of nested ifs and have a single return path? Ex instead of just having the if(error) you then have an else { } and put the rest of the code in there. Is that considered better practice?
I've actually seen people use goto in situations like this, but I don't think that's considered a practical thing either.