Re: Problems w/ goto

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, Dec 20, 2010 at 7:45 PM, David Hutto <smokefloat@xxxxxxxxx> wrote:

> Is the problem with using the goto convolutedness(as I've seen other
> senior programmers in other languages when explaining, or 'showing
> off'), or is their an actual functional problem with it?


It works perfectly well and is a great solution in extremely limited cases.
The problem is that it can be used in many cases where other control flow
statements are more clear. It was more of a problem before because people
came from languages that had goto but not the other high-level control flow
statements. Using goto often leads to hard-to-follow code.

For example, rearranging the above code yields

    do {
        if (!acquireTarget()) {
            break;
        fireMainCannon();
        fireMissiles();
    } while (enemiesInView());

Even this doesn't get away from using break--a special form of goto for
loops. One way around that is to introduce a loop variable like $done, but I
think break is cleaner here. Sometimes goto, break, and continue are simply
the best tools for the job. I wouldn't say "never use goto," but I do feel
that 99 times out of 100 you're probably better off using something else.

One thing to keep in mind is that under the hood the PHP interpreter turns
while(), for(), etc. into a bunch of gotos.

    for ( <init> ; <check> ; <increment> ) <block>

is just a shorter way to write

    <init>
    goto check;
loop:
    <block>
    <increment>
check:
    if (<check>)
        goto loop;

The same can be done for all the other control flow statements.

David

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux