code

누구든지 여전히 C #에서 [goto]를 사용합니까? 그렇다면 그 이유는 무엇입니까?

codestyles 2020. 8. 25. 08:04
반응형

누구든지 여전히 C #에서 [goto]를 사용합니까? 그렇다면 그 이유는 무엇입니까? [닫은]


누군가가 여전히 C #에서 "goto"키워드 구문을 사용하는지 여부와 그 이유가 무엇인지 궁금합니다.

나는 독자가 코드를 훑어 보도록 만드는 어떤 진술을 나쁜 습관으로 보는 경향이 있지만 그러한 구문을 사용하는 데 신뢰할 수있는 시나리오가 있는지 궁금합니다.

Goto 키워드 정의


goto가 실제로 가독성을 향상시킬 수있는 (드문) 경우가 있습니다. 실제로 링크 한 문서에는 두 가지 예가 나열되어 있습니다.

goto의 일반적인 용도는 제어를 특정 switch-case 레이블 또는 switch 문의 기본 레이블로 전송하는 것입니다.

goto 문은 깊이 중첩 된 루프를 벗어나는데도 유용합니다.

다음은 후자의 예입니다.

for (...) {
    for (...) {
        ...
        if (something)
            goto end_of_loop;
    }
}

end_of_loop:

물론 코드를 함수로 리팩토링하거나 주변에 더미 블록을 사용하는 등이 문제를 해결하는 다른 방법도 있습니다 (자세한 내용은 이 질문 참조). 참고로 Java 언어 디자이너는 goto를 완전히 금지 하고 대신 레이블이 지정된 break 문을 도입 하기로 결정했습니다 .


이 부분이 기억 나

switch (a)     
{ 
    case 3: 
        b = 7;
        // We want to drop through into case 4, but C# doesn't let us
    case 4: 
        c = 3;
        break; 
    default: 
        b = 2;
        c = 4;
        break; 
}

이와 같은 것에

switch (a)     
{
    case 3: 
        b = 7;
        goto case 4;    
    case 4: 
        c = 3;
        break;     
    default: 
        b = 2;
        c = 4;
        break;
}

이것을 참조하십시오


C # 5에서 비동기 메서드를 사용할 때 컴파일러가 생성하는 코드의 종류를 보여주기 위해 Eduasync 에서 광범위하게 사용합니다 . 반복자 블록에서도 동일한 것을 볼 수 있습니다.

"일반"코드에서는 마지막으로 사용한 시간이 기억 나지 않습니다.


goto is great for breaking out of many loops where break would not work well (say upon error conditions), and as Kragen said goto is used by the compiler to generate switch statements and some other things as well.


I don't remember ever using goto. But maybe it improves the intent of a forever loop that you really never want to exit (no break, but you can still return or throw):

forever: {
  // ...
  goto forever;
}

Then again, a simple while (true) should suffice...

Also, you could use in a situation where you want the first iteration of a loop to start in the middle of the loop: look here for an example.


The compiler uses goto statements in various pieces of generated code, for example in generated iterator block types (generated when using the yield return keyword - I'm pretty sure that the generated XML serialisation types also have a few goto statements in there somewhere too.

See Iterator block implementation details: auto-generated state machines for some more details on why / how the C# compiler handles this.

Other than generated code there isn't a good reason to use a goto statement in normal code - it makes the code harder to understand and as a result more error-prone. On the other hand using goto statements in generated code like this can simplify the generation process and is normally fine because nobody is going to read (or modify) the generated code and there is no chance of mistakes being made because a machine is doing the writing.

See Go-to statement considered harmful for an argument against goto as well as a classic piece of programming history.


The processor implements at least one jump instruction and I'm sure lots of statements use those in thier implementation or interpretation.

One of the good things about using a 3rd or 4th generation langauge is that these physical details are abstracted away from us. Whilst we should be mindful of the law of leaky abstraction I think that we should also use our tools as they are intended (sorry). If I were writing code and a goto seemed like a good idea, it would be time to refactor. The purpose of a structured language is to avoid these "jumps" and to create a logical flow in our engineering.

I should avoid the use of break but I can't overlook the performance benefit. However, if I have nested loops that mutually need to break it is time to refactor.

If anybody can propose a use of goto that seems better than refactoring I will gladly withdraw my answer.

I hope I'm not guilty of rushing to the "bike shed" here. Like Kragen says, whats good enough for Dijkstra is good enough for me.


Goto is never better. And continue, break (except in switch/case), (multiple) return, and throw should also be kept to the barest minimum. You never want to escape from the middle of nest loops. You always want the loop control statements have all the loop control. Indenting has information, and all these statement throw that information away. You might as well take out all the indenting.

참고URL : https://stackoverflow.com/questions/6545720/does-anyone-still-use-goto-in-c-sharp-and-if-so-why

반응형