Question

The "goto" statement comes straight out of ASM or any other assembler language.

Here's a link: http://be2.php.net/manual/en/control-structures.goto.php

I'm wondering: what can this do to make my code more well-organized? How can I implement this in larger projects, without screwing it up. Since the goto will allow you to jump back and forth, accidental assignments and infinite loops are waiting to happen if you use this the wrong way.

Can someone give me an example of a good use of this?

EDIT: allright, I've seen some of the replies and apparently a wide consensus exists about the use of the "goto" statement and it being bad.

So I'm still wondering: why would PHP bother to add it to the language. If they didn't see something in it, they wouldn't do it... so why?

Also: A discussion here on StackOverflow about "goto" in general

EDIT2: Seeing as this question induced a lot of bad things to be sad about the goto statement, I went and asked my father. He's 52 years old and is an Industrial Engineer.
He told me a couple of times he did a good amount of programming in his days and mostly in FORTRAN and COBOL. Nowadays he does IT services, server&networkmanagment and such.

Anyways, he said some stuff about "back in my day..."
After discussing that a bit, he came back to the goto statement, saying that even back in his days as a student, they allready knew it wasn't a smart idea to use it, but they didn't have much better back then. Try/catch was still years away and error handling hardly excisted.
So what did you do to check your program? Add a few lines at the end that allow you to print output and everything you need to check in your code, and then you place the line: "goto printing;", or something like that, to start the printing of your data.

And in this manner, you gradually debugged your code.

He agrees that the use of goto in the modern programming world is pretty useless. The only use he finds justified is an "emergency break", to be used in extreme debugging and unexpected situations. Kinda like goto fatal_error;, and have the "fatal_error" part of your code do some things to show you in-depth results.
But only during the creation of something. A finished product should not have goto-statements.

LATE EDIT: Another discussion about "goto" in PHP5.3/PHP6

Was it helpful?

Solution

If you're writing good PHP code, you shouldn't need to use goto. I think it's a mistake that they're adding it in, as it just leads to lazy programming.

See

http://www.procata.com/blog/archives/2004/07/29/goto-in-php/

For a good commentary on the addition of this to PHP, and also, here on stack overflow,

GOTO still considered harmful?

OTHER TIPS

I have only ever found two uses for goto:

  1. To break out of nested loops. But most newer languages have a mechanism to do this without goto anyway (break <number> in PHP, or break <loop label> in Java, etc.).
  2. To go to a cleanup section at the end of a function. But again, this isn't often useful in a garbage-collected language.

In other words, if you don't know whether you should use goto for something, you shouldn't.

The main use I see in having gotos in a language is the ability to port across languages. I wrote a parser generator in C that generated parsers with gotos (because it was easier to use gotos than to implement more sane control structures), and now porting it to PHP isn't as much of a headache.

goto can help reduce code duplication for stack unwinding, in pseudo code below:

do A
if (error)
    goto out_a;
do B
if (error)
    goto out_b;
do C
if (error)
    goto out_c;
goto out;

out_c:
undo C

out_b:
undo B:

out_a:
undo A

out:
return ret;

( Pseudo code by Robert Love, taken from the linux kernel archive mailing list: https://lkml.org/lkml/2003/1/12/203 )

It can be used for debugging purposes so you don't have to comment out or refactor blocks of code just to temporary change the workflow.

In Classic VB coding, use of goto is handy for emulating try/catch error handling like this:

Function MyFunction() as String

'-- start of error block
'
 On Error Goto Catch
   ' do something here that might cause an error
   MyFunction = "IT WORKED"
   Exit Function

 Catch:
   ' error occured - do something else
   MyFunction = Err.Description

 '
 '-- end of error block

End Function

... and here is a way to emulate the try/catch/finally ..

Function MyFunction() as String

'-- start of error block
'
 On Error Goto Catch
   ' do something here that might cause an error
   MyFunction = "IT WORKED"
   Goto Finally

 Catch:
   ' error occured - do something else
   MyFunction = Err.Description
   Err.Clear

 Finally:
   ' put your finally code here

 '
 '-- end of error block

End Function

It can also be useful for cleanup at the end of a function, although i suppose you could make a case that another function can be called to do that cleanup.

In all honesty, I have never had an occasion in PHP where I thought to myself 'hmm, I wish there was a goto statement'. I haven't read up on why they decided to do this, but, those guys are pretty smart, and have taken PHP into very good directions so far, so maybe the are anticipating a need that we don't realize yet.

There is no such thing as good use of goto.

Maybe, just maybe, it could be useful to get out of multiple nested loops, but you can already do that using "break 2" and such. Labeled breaks like in Java would be better than goto for this purpose.

Perhaps it's also useful with code written without using exceptions, when you need to skip to the end of a bunch of statements once one fails. But that's only fixing crappy code with more crappy code.

I admit I have never used goto in my codes. :)

The only reason for me seems to facilitate the shortest migration route from other languages to PHP (practically only changing the language without touching the control structures) and refactor the code on the 2nd stage of the porting.

Personally I believe in educated colleagues and as they can avoid the conditional break-s from loops, they would be able to resist the temptation of goto.

Goto is primarily used when writing finite state machines. When parsing context free grammer you will actually need one of those. Though we could live without goto if continue $case; is a valid statement within a switch block to jump to a different case and off course having case ranges as many languages nowadays have. Until then we are pretty much stuck with goto.

Sometimes I use goto to avoid multiple nested ifs. That's not only about the logic, the structure or the program flow, sometimes it can be just about how the code looks like.

As has been said before, goto is only really required in some types of algorithms, usually those that come up in language parsing or finite state machines. I have never missed the lack of goto in PHP.

OTOH, I have programmed in a language where the only two structures were functions and conditional gotos: SNOBOL4. Since the risk of spaghetti code was so high, most SNOBOL4 programmers were/are careful to avoid that. But gotos did enable some very tight programming, creative loop executions and so on. It's actually somewhat easier to do FSM-type loops if all you have are gotos.

Generated code could make good use of goto, I guess. The good thing about generated code is that you don't need to maintain it - you just regenerate it.

goto should really be something though that was in the language and would be being made obsolete due to better programming practises. Adding it now does seem like a backwards step.

The b big advantage of gotos is learning curve. One wonders why tools like visual studia and macs do well. The reason is that people want more than a great product; they want a great product that they can learn to use in just an hour or so. Many programmers now a days only program as one of their jobs. I see so many books say that one should never use a goto and then give five or so technologies such that they say eliminate every need of it. I say that just that fact that they mentioned 5 is proof of how good the goto is!!!!! I don't have time to teach five things that include exception structures that take whole chapters to explain!!!!! when all you really need is a simple goto that can be explained in 30 seconds. Sure, you can create bad code with them if the programmer wants--- but hey, most programmers don't want to write bad code and if they did they could anyway. Most gotos in our lab made the code extremely simple to understand and learn; much more so than reading a 2000 page book.

GOTO, the restricted execution control structure, can be used in the place of loops, but that is highly discouraged. Its use tends to encourage the creation of unstructured code, which is a terrible practice. It is most likely best if used only in development, for debugging (skip large amounts of code to access a particular problem area) and testing. The only other purpose for the GOTO is possibly for writing an assembler; not likely. GOTO, if used outside of development, should be used sparingly and only as a last resort. If possible, replace a GOTO with an applicable loop structure.

As for the thread linked last (GOTO command in PHP?):

As stated by Ishmaeel (edited by Gordon; by far the best answer):

The GOTO is simply an extended BREAK, with the ability to "use static labels". "Basically, it will be enhancing the ability to break out of nested if statements."

The short answer is goto is a workaround for a limited stack space with much better performance in single threaded code. Other than addressing stack space or performance, its usage would be at least unnecessary and at most inappropriate because it causes unneeded complexity.

In over 2 million lines of code I've written in all languages, excluding machine code :-). Only twice has its use been necessary and both due to inspecting\sorting large tree datasets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top