Thread: "goto" question

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    21

    "goto" question

    I'm just a newbie in c++, and as far as i've seen, nobody seems to use the "goto" statement.

    Why? is it frowned upon? Are there any problems using it?
    Can it be used to replace an "if" or a loop? SHOULD it be used?

  2. #2
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    gotos shouldn't be used unless you absolutely have to, which are few rare cases. The reason people don't like is because using it makes the code look ugly, I'd argue that excessive use of OO is uglier though

    gotos can't replace if statements, but can replace loops. In fact, a loop is probably gotos, or JMP statements at the assembly level but I haven't bothered to look that up so don't quote me on that.
    This doesn't mean you should replace loops with gotos either.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    It's been said that if your code requires a goto, your code probably needs redesigning - and it's true. The only time I've ever personally thought about using a goto was in a heavily nested loop - but when it gets that messy, you probably ought to rethink the whole algorithm.

    In practically every situation, a different construct will do a better job, even if it's a slightly more complicated concept. At the very least, avoid using them to prevent arguments with fellow programmers.

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    The only time I've ever personally thought about using a goto was in a heavily nested loop - but when it gets that messy, you probably ought to rethink the whole algorithm.
    it doesn't bother me in the least to use a goto in that situation - you can't blame the programmer for defficiencies in the language, and the fact is the language lacks the facilities to break out of nested loops other than the clumsy loop control variables we usually resort to or goto's (exceptions can be used too, of course, but that might be a bit overkill). It would be nice if break and continue could take arguments that would map into the level of nesting to affect, but - whatever...until that day I guess we'll just have to churn out ugly code. there aren't MANY good reasons to use a goto, but that's definately on my list as one of them.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    But the situations where you have heavily nested loops with out-of-turn break conditions should be rare in the first place. Not that they don't occur, but they ought to be rare.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  6. #6
    60% Braindead
    Join Date
    Dec 2005
    Posts
    379
    You can always break from several loops at once. If you want to break from every loop at once, turn your whole loop into a void function and use return. That even makes your code look better if its a big loop :P. The alternative, is an if statement after every for.

    Code:
    for(a=0; a < 10; a++) {
     if(SomeBOOL == false)
      break;
     for(b=0; b < 10; b++) {
      if(SomeBOOL == false)
       break;
      cout << a << b << endl;
      SomeBOOL = true;
     }
    }
    That gets alot uglier than a goto statement though. I'd stick with happy little functions .
    Code:
    Error W8057 C:\\Life.cpp: Invalid number of arguments in function run(Brain *)

  7. #7
    Registered User
    Join Date
    Feb 2006
    Posts
    21
    Thanks everyone... now... is goto slower than a well structured loop or normal code?

  8. #8
    Registered User Voodoo Doll's Avatar
    Join Date
    Feb 2006
    Posts
    4
    is goto slower than a well structured loop or normal code?
    Today 07:26 PM
    Nope, it's almost always about the same speed since any high level loop construction becomes the equivalent of a goto loop when translated to machine code. Sometimes a goto is faster if you know what the optimizer does with your loops, you're pretty slick with assembly, and you take advantage of both to micromanage your high level code.

  9. #9
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    goto is as fast as it can be, it has 1:1 relationship to it's assembly instruction (JMP) I believe.
    There shouldn't be an performance difference if you replaced a loop with gotos, your code will just get nastier.

  10. #10
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    The code

    Code:
    while (n == 1) {
      foo();
    }
    is equivalent to

    Code:
    top:
    if (n != 1)
      goto end;
    foo();
    goto top;
    end:
    Their running time depends on what the compiler wants to do. If the compiler wants to, it can have your program wait ten seconds everytime a goto statement is executed. It could do the same for a while loop. Unless you're looking at the source code for your compiler or unless you analyze the output of your compiler, there's no way to be able to tell what your compiler will do. Generally speaking, there's no reason one would be compiled faster than the other, and they could very well likely be compiled to the exact same code. Well, your compiler might use a slightly different way of ordering your code in the while loop, and the way it picks might tend to be slightly faster. Maybe.

    Ignore the people who say goto is bad. Instead, write your own programs using goto and for loops and whatnot -- whatever you find appropriate.

  11. #11
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    In case anyone's interested, here's some disassembly my compiler gives me:
    Code:
      while (n == 1) {
    00411A88  cmp         dword ptr [n (428500h)],1 
    00411A8F  jne         main+38h (411A98h) 
      foo();
    00411A91  call        foo (4112F3h) 
      }
    00411A96  jmp         main+28h (411A88h) 
    }
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  12. #12
    pwns nooblars
    Join Date
    Oct 2005
    Location
    Portland, Or
    Posts
    1,094
    I have been programming for about 3 years now, and now I program apps/tools for a living. I have never needed a goto statement. In the few cases I thought I did, after looking at my code, I realized it was so far from optimized that it needed a rewrite anyway. So when I rewrote it I kept in mind where I thought I needed the goto statement and found that my newer code is faster than my old using a goto. This is not because goto is slower, but once you optimize your code and rewrite after you have hit all the walls on the way (this is where it helps to psuedo code a bit atleast) so that it is more streamlined, you will find you never really needed it in the first place.

    Over time you will write code the doesn't need rewrites because you can plan ahead better since you know the langauge better. While you are learning unless you have a MESS of nested loops, when you think you need a goto, go back and rethink that section of code. And don't forget commands like continue; and break; both of which are great for parsers if you are looking for more speed.

  13. #13
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    The ease of just having "goto" and a label somewhere is by far cancelled out by the difficulty of foreseeing all the consequences of that little jump. Maybe in a scripting language it's okay, but in a language as structued as C++ there's all sorts of little issues you have to worry about.

  14. #14
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    as a practical example, consider the following often used construct:

    Code:
    bool done = false;
    
    while(a && !done)
    {	
    	while(b && !done)
    	{
    		while(c && !done)
    		{
    			if(x)	done = true;
    		}
    	}
    }
    compared to:

    Code:
    while(a)
    {	
    	while(b)
    	{
    		while(c)
    		{
    			if(x)	goto done;
    		}
    	}
    }
    
    done:
    the second version both faster and more readable.

    >> In case anyone's interested, here's some disassembly my compiler gives me:

    I've noticed that compilers always seem to use that format. a more efficient way would be to restructure the loop by putting the comparison at the bottom, followed by a conditional jump to the top. before entering the loop initially there would be a jump to the comparison. as an example:

    ** standard form **
    Code:
    mov n, 0
    loop:
    cmp n, 10
    jz end
    inc n
    jmp loop
    end:
    ** suggested form **
    Code:
    mov n, 0
    jmp once
    loop:
    inc n
    once:
    cmp n, 10
    jnz loop
    the second form would be faster because reduces the number of instructions within the loop by one.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  15. #15
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    While it's true that goto i inconvenient for writing programs efficiently that need to work correctly and be readable, it is not bad for beginners learning how to think and how to solve problems. If you remove goto from a beginner's repertoire, he or she will be limited to thinking of solutions that use loops and conditionals in predictable patterns. The same goes for any language construct, such as closures and continuations.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM