Why is goto poor practise? [duplicate]

狂风中的少年 提交于 2019-12-02 02:08:23

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.

Alex Fort

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

It can rapidly lead to spaghetti code.

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.

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();
    }
}

GOTO short circuits your control flow, thereby undermining your design and opening the door to debug and maintenance nightmares.

Readability becomes a problem, and flow of logic can have unintended effects by the use of goto.

I think its funny that the .net compiler will change some case/switch statements to use goto.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!