Why is goto poor practise? [duplicate]

2019-07-09 02:57发布

This question is a duplicate of Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

标签: goto
8条回答
何必那么认真
2楼-- · 2019-07-09 03:30

It can rapidly lead to spaghetti code.

查看更多
手持菜刀,她持情操
3楼-- · 2019-07-09 03:34

In some cases it makes sense. But, in the majority of cases use of it it considered poor practice because it can make the execution path of code tricky to read compared to using structured code such as for loops and while loops.

When you look at a goto or a label, you don't really know where is goes to or comes from without reading or searching through the code for the label name. This is tricky especially if the goto doesn't fit on the same screen as the label. Compare this to a for loop or a while loop or an if.. you can tell from the structure (i.e. indenting of the code) what the execution path is.

Having said this, it sometimes is useful, especially for example when jumping out of some nested for loops that are digging for a particular value inside a multi-dimensional array. You could use a goto here to jump out of the for loops when the correct value is found.

查看更多
▲ chillily
4楼-- · 2019-07-09 03:41

Note that Djkstra wrote "GOTO Considered Harmful", not "GOTO Considered Deadly". It has its places. Unfortunately, the judgement to know when to use it comes after you've got some experience in maintaining other people's code, especially code that was written years ago by people who no longer work in your company. Thus, it's best to avoid goto as much as you can until you have that experience.

查看更多
We Are One
5楼-- · 2019-07-09 03:41

It encourages bad coding style, basically. See: Goto Considered Harmful [pdf]

查看更多
狗以群分
6楼-- · 2019-07-09 03:44

Because the structure of the code can be difficult to follow.

This

y:
// do more stuff
goto x

p:
// do stuff
// then done
goto y;

x: 
  // do a bunch of stuff
  if (...)
      goto y;
  else
      goto p;

done:

is much less clear than

int main()
{
    x();
}


function p()
{
    if (...)
    {
         return;
    }
}


function x()
{
    if (...)
    {
         return;
    }
    else 
    {
         p();
    }
}
查看更多
该账号已被封号
7楼-- · 2019-07-09 03:45

It means you haven't designed the code procedurally.

If you build your whiles and ifs properly, you should rarely ever need goto.

Rarely is the key word. There are times where it's useful. In that sense, many people nowadays just explicitly throw and catch exceptions, just to avoid the dreaded goto.

查看更多
登录 后发表回答