Re: Particular Example about why should we not use GOTO
"Alexander Block" <ablock84@googlemail.com> wrote in message
news:1175170788.391227.97830@o5g2000hsb.googlegroups.com...
On 29 Mrz., 09:54, "SoftEast" <hemendra.sw...@gmail.com> wrote:
Hi Buddies,
I have read a lot of stuffs regarding not using GOTO statements to opt
a good programming style [Refhttp://david.tribble.com/text/goto.html].
Can anybody give a particular lines of code which shows harmfullness
of GOTO.
SoftEast...
I use it in Mobile Development for error handling and clean up.
Normally I would use
exceptions for that, but this would be to much overhead for mobile
phones. Here is an example:
bool DoSomething() //returns false on failure
{
SomeObject* obj1 = NULL, obj2 = NULL;
obj2 = new SomeObject();
if(!ThisMayFail(obj1))
goto failed;
obj2 = new SomeObject();
if(!ThisMayFail(obj2))
goto failed;
return true;
failed:
if(obj1 != NULL)
delete obj1;
if(obj2 != NULL)
delete obj2;
return false;
}
I think this kind of clean up technique is easy to understand and
maintain.
bool DoSomething() //returns false on failure
{
SomeObject* obj1 = NULL, obj2 = NULL;
try
{
obj2 = new SomeObject();
if(!ThisMayFail(obj1))
throw;
obj2 = new SomeObject();
if(!ThisMayFail(obj2))
throw;
return true;
}
catch(...)
{
if(obj1 != NULL)
delete obj1;
if(obj2 != NULL)
delete obj2;
return false;
}
}
Undserstanding that this code isn't deleting obj1 and obj2 on success, just
as the original code wasn't.
There are always alternatives to useing goto.
Of course, you may have intended success to fall through to the cleanup, but
it didn't because you were returning before you got there. Which is the
problem with goto's, it obfuscates code.