Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Goto statements

  1. Sep 20, 2007 #1
    Some find it alright if it simplifies code, while others deem it absolutely unacceptable.

    So what's the general consensus regarding their use?
     
    Last edited: Sep 20, 2007
  2. jcsd
  3. Sep 20, 2007 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You have heard of Djikstra, haven't you?

    A goto can be preferable to alternatives in some cases:
    • handling of exceptional cases, particularly in a language such as C
    • breaking out of a deeply-nested loop
    • complying with a rigid "single point of return" rule.

    With the exception of one year on a project where the manager was a single point of return1 nazi, I have used very few goto statements per decade for the last three decades. They are hard to justify. In a project with code reviews, the user of a goto had better be very prepared for the inevitable broadside attack. Nearly every use of the goto can be eliminated with appropriate use of if/then statements and some boolean algebra. The justification is that the cure (the extra nesting and extra logic) is worse than the disease (the goto statement, of course).

    1 The ugly code and the use of gotos that inherently and inevitable results from making "single point of return" a dictum is, to me, proof that applying this guideline as a hard-and-fast rule is wrongheaded.
     
  4. Sep 20, 2007 #3

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    These days you just use exceptions which are merely gotos with a much more complicated syntax.
     
  5. Sep 20, 2007 #4
    my boss use lots of goto and his code is unreadable !
    If you are working in a team, or your code will be read by someone else, avoid using it.
     
  6. Sep 20, 2007 #5

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Not all languages support exceptions, and not all projects allow their use.
     
  7. Sep 20, 2007 #6

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    The goto has been viewed as evil since 1968 (or before) and in almost all cases is not needed. Your boss needs to read Djikstra's paper.
     
  8. Sep 20, 2007 #7

    jim mcnamara

    User Avatar
    Science Advisor
    Gold Member

    The reason he's a single-point-of-return nazi is:

    Static code metric analysis software that determines McCabe's cyclomatic complexity value, goes 'beserk' over a lot of embedded returns. Shying away from good code management practices which require a lot of effort, managers in large companies opt for this kind of software which just spews out Halstead numbers and complexity values.
    It's easy to look at '42' and say 'it's over 41. fix it'

    Your manager probably came from an environment like that. Or maybe he's creating one.
    Metric software has a place, but it shouldn't be God.
     
  9. Sep 20, 2007 #8

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    In C, you can usually replace a simple clear goto statement with half a dozen convoluted breaks, continues, and at least 10 local variables with confusing names to keep track of incomprehensible logical conditions, if your local programming guru says "gotos are always bad".

    There's a technical term for this. It's called "revenge".
     
  10. Sep 20, 2007 #9

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Code analyzers shouldn't go beserk over a return or goto. A return statement (or a goto) should not change the cyclomatic complexity of a function at all. It is the if statement wrapped around the return or goto that bumps the complexity. I have used many tools that count incorrectly. Perhap your management uses such a tool? (Example: simple straight line code should have a cyclomatic complexity of 1; many tools report this as zero so the complexity values for multiple functions can be added.)

    Actually, this manager came from an environment where unfetterred use of embedded return statements caused resource problems (e.g., leaks). He carried that experience over and mandated single point of return.

    Regarding metrics, they certainly do have their place. Fixing a function with a cyclomatic complexity of 42 sounds reasonable: How would you verify/validate such a beast? I have always viewed Halstead's metrics as a bit suspect. Anything that has to use "thoughts per second" as a scale factor (actually, "mentations per second") has to be a bit dubious.
     
  11. Sep 20, 2007 #10

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    A goto should be used whenever it makes the code easier to read!

    Typically, this involves making the code most resemble the algorithm you're trying to implement. Another circumstance that hasn't been mentioned is when you have code that should only be executed when your loop finishes normally:
    Code (Text):

    for(p = 2; p*p <= N; ++p) {
    if(N % p == 0) { goto found_factor; }
    }
    printf("N is prime!");
    found_factor:
    // continue along
     
    (Compile-time) state machines are another good candidate for using goto's.
     
  12. Sep 20, 2007 #11

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    I was trying to be funny - to avoid the simple "goto error:" in the middle of a complex loop we now have exceptions which are exactly the same thing only more confusing.

    Alephzero put it much better - I have suffered code where every statment was surrounded by layers of " if (bStatus) " to avoid having a goto.
     
  13. Sep 20, 2007 #12

    jim mcnamara

    User Avatar
    Science Advisor
    Gold Member

    DH - cyclomatic complexity is very much affected by return statements. It increases cyclomatic complexity. Period. Argue with Tom McCabe, not me. 'berserk' is my term to indicate what I personally think is an over-reaction.
     
  14. Sep 20, 2007 #13

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    I see, and I agree. Wrapping a bunch of code in a try/throw/catch pile of complexity to avoid a simple and obvious "goto error", is taking the "gotos are evil" one step too far. One of my firmest rules of programming is that unyielding rules are evil. :biggrin:
     
  15. Sep 20, 2007 #14

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    I always thought that 'throw' should be called 'not_a_goto_honest' :biggrin:
     
  16. Sep 20, 2007 #15

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    ... and catch should be called 'come_from'.
     
  17. Sep 20, 2007 #16

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    Which could be argued about, since the code after found_factor will still be executed after printing the "N is prime" message.

    I'd write
    Code (Text):

    for(p = 2; p*p <= N; ++p) {
    if(N % p == 0) { found_factor = true; break; }
    }
    if (!found_factor) { printf("N is prime!"); }
    // continue along
     
    or, if there is more extensive code than a print, even something like
    Code (Text):

    void found_factor(int factor) {
      printf("N is not prime, it has %d as a factor", factor);
    }

    for(p = 2; p*p <= N; ++p) {
    if(N % p == 0) { found_factor(p); break; }
    }
    // continue along
     
    (Long time no programming C, so not responsible for syntax errors :smile: - you get the point)
     
  18. Sep 20, 2007 #17
    Exception propagation in C++ does stack unwinding. I didn't think goto did that.

    Real programmers use "comefrom".
     
  19. Sep 20, 2007 #18

    jim mcnamara

    User Avatar
    Science Advisor
    Gold Member


    I thought real programmers used setjmp() and longjmp(). :)
     
  20. Sep 20, 2007 #19

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    No - real programmers modify the executable image on the fly
     
  21. Sep 20, 2007 #20

    rcgldr

    User Avatar
    Homework Helper

    Why is it that multple return's are acceptable, but not even one goto? Essentially, they're almost the same, causing a break in the stream of code flow.

    Regarding the comment about goto's losing popularity back in 1968, that's hard to believe considering all the Fortran programming still going on at that time.

    I guess the perspective on goto's is different for us old guys that were programming back in the 1960's (1968 for me) and 1970's before there was an "anti-goto" mystique, similar to motorcyclists from the 1960's when British bikes where better than Harleys, or 1970's when Japanese bikes were better than both and not shunned, I never got the "Harley" mystique.

    Regarding this:
    Code (Text):

    for(p = 2; p*p <= N; ++p) {
    if(N % p == 0) { found_factor = true; break; }
    }
    if (!found_factor) { printf("N is prime!"); }
    else{...}
    // continue along
     
    Being old school, I have a problem whenever the same descision is made twice in program (one extra "if" and a varible used to avoid a goto), which goes along with the fewer the number "if" statements, the better the program.

    In the situation where failure in a step stops the flow of a series of steps, I prefer "goto" to setting a status variable and constantly checking "if(status == good){ ... continue}", since you have to search the code to find if or where the first sequence that isn't conditional on "status == good". Worse yet is the nested "if{...if{...if{...}else{...}}else{...}}else{...}" where the code to handle the other branch from the first if is as far as possible from the original "if".

    Sometimes a goto is just more readable, especially when used for exception conditions.

    if(exception_condition == TRUE)goto xyz;

    I prefer to have the main flow of a routine to not appear as conditionalized such as the if(status == GOOD){ ... conditionalized, indented, but otherwise main flow of code ...}

    Sometimes the action for a test is deferred, the test is done at one point, and the action is done at a later point in the code (or maybe in several places later in the code). I liked Fortran's computed goto for dealing with these cases. For C, I use functions, and pointers to functions to accomplish essentially the same thing, setting one or more pointer to functions based on a condition that sets the "state" of a following sequence of code. If C had pointers to labels in code, it would accomplish the same thing as Fortran's computed goto. Granted that this is rare, but it is somewhat common practice to use a set of pointers to functions to represent the state of a program.

    Fortan has computed gotos, and C has pointers to functions, close enough. IBM's mainframes include an machine launguage instruction "Execute" that adds a third register based parameter to an otherwise two parameter instruction, which is close to modifying executable code.
     
    Last edited: Sep 20, 2007
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Goto statements
  1. Switch Statements (Replies: 1)

  2. Fortran 90, goto (Replies: 13)

Loading...