to goto or not to goto

Status
Not open for further replies.
baronvongogo said:
well, say I activate a lot of things such as:

void something(){

workstart:
work1
work2
work3
work4

if (work1 <=0)
goto workstart;
}



do
{
work1
work2
work3
work4
}
while(work1<=0)

that would be a much better way to do the exact same thing without using a go to statement.
 
I agree that in small programs it can be useful but if you get used to using them and don't learn how to do things the proper way your code will be impossible to debug. Seriously, I have been sitting in front of the computer looking at my own code from when I first started programming and thinking "What was this idiot trying to do." then I realize "Hey that idiot was me".
 
TheHeadFL pretty much said everything I was going to say when I read the question - down to the example he posted about breaking out of multiple loops :confused:.. Perhaps, both of us have read the same books. lol

Traditionally, don't do it. It makes for poorly organized code which is difficult to read. There are always alternatives to using the "goto". The example mentioned, is one exception to the rule - where it is actually more "clearer" to use goto. But, keep in mind that "most of the time", the situation will not call for a goto statement and will be considered to be poor style.
 
TheHeadFL said:
I feel I need to clarify my statement.

For example...

Code:
for (something)
   {
   for (something)
   {
      for (even something else yet)
      {
         if (condition) {
         // Get out of all the loops
         }
      }
   }
}


there a couple easy ways to do this without goto. 1. make all for statment exit by setting conditions in the if for example.

Code:
int main ()
{
	
	for(int i=0;i<10;i++)
	{
		cout<<i<<" "<<endl;
		for(int j=0;j<10;j++)
		{	cout<<j<<" "<<endl;
			for(int k=0;k<10;k++)
			{
				cout<<k<<" "<<endl;
				if(k==2)
				{
					i=20;
					j=20;
					k=20;
				}

			}
		}
	}

	return 0;

}

I admit that could become a long if statement if you had 50 or 60 for statements which brings me two the secound way I would do it. I would just make the whole nested for a int function and in the if statment have it return 0 which would exit the function and the loop.

The goto I guess would work too but if any of my teachers ever saw a goto statment in one of my program that would be a automatic many point off.
 
Status
Not open for further replies.
Back
Top Bottom