Usage of "goto" - what's your opinion?

Hello,

I've been dealing with a program for some hours and I finally solved it :), but I had to draw upon the "goto" sentence. I don't see any other way to modify the program since when it reaches certain condition I have to execute a some code above the current line.

My question is: what do you think about the usage of "goto"? does this exhibits poor programming abilities? Is it recommended to avoid "goto" sentence?

Cheers!
Last edited on
Can we see the program? I've never yet needed to use a goto.
@Mats: Sure. It is a DFS for a Graph:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void DFS(int s)
{
	bool* isVisited=new bool[V];
	for (int x=0;x<V;x++)
	{
		isVisited[x]=false;
	}
	
	list<int> stack;

	stack.push_back(s);
	isVisited[s]=true;
	cout<<s<<" ";
	
	list<int>::iterator i;
	
start:
	while (stack.empty()==false)
	{
		i=adj[stack.back()].begin();
		while(isVisited[*i]==true)
		{
			i++;
			if(i==adj[stack.back()].end())
			{
				stack.pop_back();
				goto start;
			}
		}
		isVisited[*i]=true;
		stack.push_back(*i);
		cout<<*i<<" ";
	}
}
Perhaps the first reasonable use of goto I have ever seen on this forum!
I would probably just use recursion here instead of emulating it with a stack/gotos.
closed account (o1vk4iN6)
I believe one of the things to avoid is goto's going back up as that's where infinite loops are created.

Could do something like this instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

	while (stack.empty()==false)
	{
                auto size = stack.size();

		i=adj[stack.back()].begin();
		while(isVisited[*i]==true)
		{
			i++;
			if(i==adj[stack.back()].end())
			{
				stack.pop_back();
				break;
			}
		}

                if(size == stack.size())
                {
			isVisited[*i]=true;
		 	stack.push_back(*i);
			cout<<*i<<" ";
                }
	}
Last edited on
@All: Thanks for your comments! Based on them, I believe "goto" usage depends on the situation. In this case it may apply, but just as @firedraco suggests, it may be better to use recursion. It would be more elegant as well :P

I'm going to try the recursive alternative and I will post it once it works.

Cheers!
closed account (Dy7SLyTq)
One is when ur using switches inside of loops
closed account (S6k9GNh0)
goto statements are often used in parser generators for some reason. There has to be some validity to it.
I remember working with someone who spent days trying to refactor code to get rid a single goto statement. There was absolutely no benefit to spending effort to refactor all the code, other than perceived aesthetics.
Topic archived. No new replies allowed.