Re: GOTO operator

From: Date: Fri, 30 Jul 2004 14:35:40 +0000
Subject: Re: GOTO operator
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-11669@lists.php.net to get a copy of this message
Paul G wrote:
function pseudocode() {
    $a=allocate_resource_z();
    $b=allocate_resource_y();
    $res=do_stuff();
    if(!$res)
        goto err_out;
    $c=allocate_resource_x();
    $res=do_more_stuff();
    if(!$res)
        goto err_out;
    $d=allocate_resource_foo();
    $res=do_even_more_stuff();
    if(!$res)
        goto err_out;
    return true;
err_out:
    free_resouce($a);
    free_resouce($b);
    if(isset($c)) free_resouce($c);
    if(isset($d)) free_resouce($c);
    return false;
}
While this is valid, it's not really a good example of pseudocode that requires a goto to be efficient. You could do the same thing with try/catch/throw: function pseudocode() { $a=allocate_resource_z(); $b=allocate_resource_y(); try {
    $res=do_stuff();
    if(!$res)
      throw SOME_ERROR;
    $c=allocate_resource_x();
    $res=do_more_stuff();
    if(!$res)
      throw SOME_ERROR;
    $d=allocate_resource_foo();
    $res=do_even_more_stuff();
    if(!$res)
      throw SOME_ERROR;
    return true;
} catch SOME_ERROR {
    free_resouce($a);
    free_resouce($b);
    if(isset($c)) free_resouce($c);
    if(isset($d)) free_resouce($c);
    return false;
} } This is also one of the reasons languages like Ada have named code blocks for exceptions. Here's some ada-like pseudo-code: BEGIN a := allocate_resource_z(); b := allocate_resource_y(); res := do_stuff(); if (!res)
    raise some_exception;
c := allocate_resource_x(); res := =do_more_stuff(); if (!res)
    raise some_exception;
d := allocate_resource_foo(); res := do_even_more_stuff(); if(!res)
    raise unknown;
return TRUE; EXCEPTION free_resouce(a); free_resouce(b); if (c) free_resouce(c); if (d) free_resouce(c); return FALSE; END The case that Ilia and the other main developers is not for cases like this. If you look through the Linux kernel, you can see very good examples of goto usage that is not related to this kind of error handling. It's mainly to jump around inside parsing code while maintaining a stack, so the same chunk of code can continuously handle the same source of input without hundreds of if statements and indented blocks. -- Shaun M. Thomas INN Database Administrator Phone: (309) 743-0812 Fax : (309) 743-0830 Email: sthomas@townnews.com Web : www.townnews.com

« previous php.internals (#11669) next »