Problems that can arise from using a GOTO statemen

2019-08-26 13:41发布

Is there any harm for using a GOTO statement to jump down only ? Or are we totally safe ?

What I mean by that is think this as my code,

Some code ...
...

GOTO whereToJump

Some code ...
...

whereToJump: 

Some code ...

When whereToJump point is always below the GOTO statement, is there any security issues?

标签: c# goto
8条回答
淡お忘
2楼-- · 2019-08-26 14:07

I use goto statements when it is needed to jumb to a code block from many locations downward. Usually without goto statement, this may require to write another function (so that the code block above is not repeated in the first function) and call inside the first. goto is no less efficient than if or switch statements since it also utilizes one of the jumb statements (jz, jnz, etc) which are used by if, switch, etc.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-26 14:11

This is subject of one of the most famous computer science papers. Go To Statement Considered Harmful by Dijkstra. It essentially states that noone ever needs goto (I know there are a few exceptions as always).

It is 1968 but still very readable today.

查看更多
疯言疯语
4楼-- · 2019-08-26 14:13

In any more complicated example, surely if you can decide to use the GOTO only to jump forward in the same scope, you could use an if statement. (If it's not in the same scope, it's not really "just jumping forward", is it?)

(And, of course, if your real code is not more complicated than that, you could just get rid of that second block of "Some code...")

查看更多
够拽才男人
5楼-- · 2019-08-26 14:20

goto does not make the code less safe independent of which way you jump.

You structure your code any way you like. It is your code that decides if the code is good/bad. goto maybe appropriate in some cases (no I can's show an example :-) )

The problem with goto is that it may hide the flow of execution in the program and make the code confusing. But if you create easy to read/maintain code then that is not a problem.

查看更多
虎瘦雄心在
6楼-- · 2019-08-26 14:21

The cardinal reason why GOTOs should be avoided these days is that programmers in general are not used to GOTOs any more (which is a good thing). So if you write code that makes extensive use of GOTOs, chances are your fellow programmers will have difficulty understanding and extending it.

Worse, a GOTO here and there may lead to Broken Window Syndrome as colleagues begin to use more and more GOTOs until you're left with a big bowl of spaghetti.

xkcd puts it best...

alt text

查看更多
来,给爷笑一个
7楼-- · 2019-08-26 14:26

Well, there's really no problem. That code is equivalent to:

Some code ...
...

if (false)
{
Some code ...
...
}

Some code ...

That said, I wouldn't do it. Good use cases for goto are really rare, and other flow control constructs are more idiomatic in C#.

查看更多
登录 后发表回答