Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


To goto or not to goto?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
93 replies to this topic

Poll: To goto or not to goto? (149 member(s) have cast votes)

How often do you use goto statements?

  1. Never (92 votes [61.74%])

    Percentage of vote: 61.74%

  2. Very rarely (43 votes [28.86%])

    Percentage of vote: 28.86%

  3. Occasionally (9 votes [6.04%])

    Percentage of vote: 6.04%

  4. Quite often (1 votes [0.67%])

    Percentage of vote: 0.67%

  5. I have made it my quest to use them at least 5 times in each function (2 votes [1.34%])

    Percentage of vote: 1.34%

  6. The language I use doesn't have this keyword (2 votes [1.34%])

    Percentage of vote: 1.34%

Vote Guests cannot vote

#81 Vortez   Crossbones+   -  Reputation: 2704

Like
0Likes
Like

Posted 19 August 2011 - 10:30 PM

I think i have a good example of a good usage of a goto in the program i am currently working on. Altrough the code
is rather long, you can really see how much this goto is usefull in this situation. This is the "master" function of
a dll, so that's why it's rather big, i stripped most of the code for simplicity reasons,

//-----------------------------------------------------------------------------
// Where all the magic's happen...
//-----------------------------------------------------------------------------
DWORD WINAPI ReadLoopThread(void *param)
{
// <initialisation code>
	try
	{
		// put program in an infinite loop of reading and writing data
		while(1) 
		{

			// Exit the loop if we've been asked too...
			if(ReadLoop.MustExitThread())
				break;

			// Is the socket ready to read?
			if(pNetServer->CanRead()){

				// Read the Header of the message
				if(!ReadPacket.IsHeaderDoneProcessing()){

					// <some code... read the socket>
					
					// Are we done reading the header?
					if(ReadPacket.GetHeaderIndx() == sizeof(PacketHeaderStruct)){

						// Take action depeding on the message
						switch(ReadPacket.Header.Msg)
						{
						case MSG_HANDSHAKING_REQUEST:
							// Read the login data and return true if sucessfull...
							if(OnHandshakeRequest(&ReadPacket, hWnd)){					
								// <some code...>
							} else {
								goto DisconnectJmp;
							}
							break;

						case MSG_QTZ_IMG_REQUEST:
							{
								// <some code...>

								if(SS.Size > 0){
									// Send the data
									if(!WriteData(SS.Buffers.QTZP.Compressed.GetBuffer(HeaderSize), SS.Size))
										goto DisconnectJmp;
								}

								// <some code...>
							}
							break;

						case MSG_MP1_IMG_REQUEST:
							{
								// <some code...>

								if(SS.Size > 0){
									// Send the data
									if(!WriteData(SS.Buffers.MPEG.Encoded.GetBuffer(HeaderSize), SS.Size))
										goto DisconnectJmp;
								}

								// <some code...>
							}
							break;

						case MSG_INPUT_DATA:
							{
								// <some code...>
							}
							break;
						}

						//-----------------------------------------------------------------------------

						ReadPacket.Reset();	
					}
				}
			}
		}
	}
	catch (...)
	{
		MessageBox(hWnd, "An Error occured in ReadLoop thread.\nPerforming Cleanup.", "Error!", 0);

		CleanupReadLoopThread(hWnd, &VideoEncoder, &OriginalDesktopColor);

		throw;
	} 

DisconnectJmp:
	CleanupReadLoopThread(hWnd, &VideoEncoder, &OriginalDesktopColor);

	return 0;
}


Sponsor:

#82 sam_hughes   Members   -  Reputation: 132

Like
0Likes
Like

Posted 19 August 2011 - 11:07 PM

I think i have a good example of a good usage of a goto in the program i am currently working on.


You can do cleanup with RAII instead.

DWORD WINAPI ReadLoopThread(void *param)
{
// <initialisation code>
	Cleanup cl([&]() { CleanupReadLoopThread(hWnd, &VideoEncoder, &OriginalDesktopColor); });
	try
	{
		// put program in an infinite loop of reading and writing data
...


#83 Flimflam   Members   -  Reputation: 657

Like
0Likes
Like

Posted 19 August 2011 - 11:34 PM

Okay.

bool bContinue = true;

for (int i=0; i<n && bContinue; ++i) {
  switch (some_array[i]) {
    case 0:
      //...
      break;
    case 1:
      if (some_condition())
        bContinue = false; // Break out of the loop, in a situation where `break' would just break out of the switch block.
      break;
    //...
  }
}
//...



I have honestly never even considered goto here, and still will never.


L. Spiro

Fair enough. I was merely stating my opinion about your proposed solution. :) Your new solution would be the one I went with as well. I have not found myself needing to use goto since my days of QBasic.

#84 Vortez   Crossbones+   -  Reputation: 2704

Like
0Likes
Like

Posted 20 August 2011 - 12:08 AM

My function cannot be encapsulated, since im using it as a thread, called by the CreateThread API.

#85 Trienco   Crossbones+   -  Reputation: 2212

Like
0Likes
Like

Posted 20 August 2011 - 01:40 AM

I think i have a good example of a good usage of a goto in the program i am currently working on.


Seems the only reason you use a goto instead of a throw is because you're lazy with your exception handling

try
{
	//goto
    throw MyHandshakeException;
}
catch(MyHandshakeException) {}
catch(...) {}

//cleanup

or use RAII as suggested, even made easier with boost

try
{
	shared_ptr<void> cleanUpOnExit(static_cast<void*>(0), 
                           	bind(CleanupReadLoopThread, hWnd, &VideoEncoder, &OriginalDesktopColor) );
...
	//goto
	return;
}
//NO explicit cleanup anymore

And how can you not "encapsulate" your function?

void runTHISinThread()
{ 	
 	ReadLoopThread();
	CleanupReadLoopThread();
}

I'm not even strictly against goto, but claiming this case justifies goto when you're even _already_ using a try-catch block is hardly convincing.
f@dzhttp://festini.device-zero.de

#86 DenzelM   Members   -  Reputation: 295

Like
0Likes
Like

Posted 20 August 2011 - 01:56 AM

I've used one goto in the say... 18 years I've been programming. It was a throwaway test app that I had to trigger cleanup code before exiting the function and had done it so slapdash that a finally block wouldn't deal with it; and it amused me to write such horrible code.

If you used a goto in production code I would fire you on the spot.

Well than you would be possibly firing Kenton Varda, Sanjay Ghemaway, Jeff Dean, and others... Oh wait, they work at Google so they don't need to work for someone as close-minded as you.
Denzel Morris (@drdizzy) :: Software Engineer :: SkyTech Enterprises, Inc.
"When men are most sure and arrogant they are commonly most mistaken, giving views to passion without that proper deliberation which alone can secure them from the grossest absurdities." - David Hume

#87 Telastyn   Crossbones+   -  Reputation: 3726

Like
0Likes
Like

Posted 20 August 2011 - 08:14 AM


I've used one goto in the say... 18 years I've been programming. It was a throwaway test app that I had to trigger cleanup code before exiting the function and had done it so slapdash that a finally block wouldn't deal with it; and it amused me to write such horrible code.

If you used a goto in production code I would fire you on the spot.

Well than you would be possibly firing Kenton Varda, Sanjay Ghemaway, Jeff Dean, and others... Oh wait, they work at Google so they don't need to work for someone as close-minded as you.


I love how this gets people's panties in a twist. And I love how people point out all these examples of very good programmers who've used the construct in very specific circumstances as proof that it's good, but completely ignore all of the catastrophic examples that lead to Go To Statement Considered Harmful.

I've said it before, and I'll say it again: There is absolutely no viable use case for goto in my working environment (C# 4).

#88 Flimflam   Members   -  Reputation: 657

Like
2Likes
Like

Posted 20 August 2011 - 11:47 AM

I love how this gets people's panties in a twist. And I love how people point out all these examples of very good programmers who've used the construct in very specific circumstances as proof that it's good, but completely ignore all of the catastrophic examples that lead to Go To Statement Considered Harmful.

I've said it before, and I'll say it again: There is absolutely no viable use case for goto in my working environment (C# 4).


I completely agree with you about there being a distinct lack of use for goto in C# but I think the reason everyone has reacted so negatively is that your first comment makes no mention of C#, where a plethora of other methods are available. It just sounded rather flamebaitish.

#89 DenzelM   Members   -  Reputation: 295

Like
0Likes
Like

Posted 20 August 2011 - 11:57 AM

I love how this gets people's panties in a twist. And I love how people point out all these examples of very good programmers who've used the construct in very specific circumstances as proof that it's good, but completely ignore all of the catastrophic examples that lead to Go To Statement Considered Harmful.

I've said it before, and I'll say it again: There is absolutely no viable use case for goto in my working environment (C# 4).

Exactly as Flimflam pointed out, you made no mention of C# in your original reply. Don't fool yourself, I pointed out good programmers who've used goto in very specific circumstances as proof that it's good in very specific circumstances. Thank you for proving my point. Posted Image
Denzel Morris (@drdizzy) :: Software Engineer :: SkyTech Enterprises, Inc.
"When men are most sure and arrogant they are commonly most mistaken, giving views to passion without that proper deliberation which alone can secure them from the grossest absurdities." - David Hume

#90 Fekete   Members   -  Reputation: 106

Like
0Likes
Like

Posted 24 August 2011 - 12:01 PM

(Assuming C, here). Anytime I need a goto, I have functions. That's what they're there for essentially. This not only allows you to move to a different address, but it also maximizes re-usability; a topic I seem to have missed being discussed. Clean-up for malloc/free will be the same regardless how you use it, so why not write your own little library to handle it for you? Goto, while making it simple and readable (I guess... but not using it ever, I can honestly say functions are far more readable for me) just shows to me that you're not thinking for the long term with your code.


#91 sam_hughes   Members   -  Reputation: 132

Like
0Likes
Like

Posted 24 August 2011 - 10:57 PM

I've said it before, and I'll say it again: There is absolutely no viable use case for goto in my working environment (C# 4).


If you have a for loop inside a for loop, you should avoid using break or continue and instead be perfectly explicit by using a goto.

#92 Telastyn   Crossbones+   -  Reputation: 3726

Like
0Likes
Like

Posted 25 August 2011 - 06:27 AM


I've said it before, and I'll say it again: There is absolutely no viable use case for goto in my working environment (C# 4).


If you have a for loop inside a for loop, you should avoid using break or continue and instead be perfectly explicit by using a goto.


1. Why? Break and continue have known behaviors, and I don't have to hunt for the label. (not that I will use continue or break in this scenario if I can help it)
2. Nesting loops and jumping out like that is a code smell of its own. If you've found what you're looking for, put it in a method and return. If you found some exceptional behavior, throw an exception.

#93 smr   Members   -  Reputation: 1676

Like
0Likes
Like

Posted 25 August 2011 - 07:46 AM

I responded "very rarely."

At my job we still have some old applications originally written in Visual Basic 6, whose rudimentary exception handling was done using the "On Error GoTo LABEL" construct. You could conceivably implement try/catch/finally using it, but was never pretty. The coder had to ensure that they were branching to the Finally code and resuming the execution when the error is handled. Also, because these were just labeled sections of code, you didn't get a new scope, so RAII wasn't a possibility in your handlers.


' This routine will raise a stack overflow error
Sub KillMe
    KillMe
End Sub

Sub DoStuff
    ' Set up error handler
    On Error Goto Catch

    ' Stack overflow here:
    KillMe
    Exit Sub ' This guards against the program stepping into the error handler when there was no error

Catch:

    Dim ErrorNumber   


    ' Keep the error code because it will be clobbered when we switch off error handling
    ErrorNumber = Err.Number

    ' Turn off error handler
    On Error GoTo 0
    If ErrorNumber = 0 Then
        ' Here's where your "catch" code would be
        GoTo Finally
    Else If ErrorNumber = 1 Then
        ' Or here...
        GoTo Finally
    End If

    ' Couldn't handle the error. Exit the program
    End

Finally:
    ' Returns execution to the line after the line that caused the error
    Resume Next    
End Sub



#94 godplusplus   Members   -  Reputation: 102

Like
0Likes
Like

Posted 30 August 2011 - 05:12 AM

I work mostly with C++, objective C or other languages that are not "pure C".
I never had the need to use a goto statement, the reason is that there are usually other ways to do things, at least in these languages. So, goto statements never really cross my mind as alternatives anyway.

The thing about goto statements is that they are easy for the computer to understand, after all, when code is compiled into assembly language, everything becomes a bunch of goto (jump) statements (basically, yeah, in assembly language, goto is the only way to go. See what I did there?).
However, we humans are more prone to messing up when doing a goto statement.

I don't think using goto is necessary, at least in the languages that I use. But if it really makes you feel better (or worse?), remember that your code will eventually be compiled into more goto statements than you can imagine.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS