goto(C# 참조)

업데이트: 2007년 11월

goto 문은 프로그램의 제어를 레이블 문으로 직접 전달합니다.

일반적으로 goto는 switch 문에서 특정 switch-case 레이블이나 기본 레이블로 제어를 전달하는 데 사용합니다.

goto 문은 깊이 중첩된 루프를 벗어나는 경우에도 유용하게 사용할 수 있습니다.

예제

다음 예제에서는 switch 문에서 goto를 사용하는 방법을 보여 줍니다.

class SwitchTest
{
    static void Main()
    {
        Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
        Console.Write("Please enter your selection: ");
        string s = Console.ReadLine();
        int n = int.Parse(s);
        int cost = 0;
        switch (n)
        {
            case 1:
                cost += 25;
                break;
            case 2:
                cost += 25;
                goto case 1;
            case 3:
                cost += 50;
                goto case 1;
            default:
                Console.WriteLine("Invalid selection.");
                break;
        }
        if (cost != 0)
        {
            Console.WriteLine("Please insert {0} cents.", cost);
        }
        Console.WriteLine("Thank you for your business.");
    }
}
/*
Sample Input:  2

Sample Output:
Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.
*/

아래 예제에서는 goto를 사용하여 중첩된 루프를 중단하는 방법을 설명합니다.

public class GotoTest1
{
    static void Main()
    {
        int x = 200, y = 4;
        int count = 0;
        string[,] array = new string[x, y];

        // Initialize the array:
        for (int i = 0; i < x; i++)

            for (int j = 0; j < y; j++)
                array[i, j] = (++count).ToString();

        // Read input:
        Console.Write("Enter the number to search for: ");

        // Input a string:
        string myNumber = Console.ReadLine();

        // Search:
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < y; j++)
            {
                if (array[i, j].Equals(myNumber))
                {
                    goto Found;
                }
            }
        }

        Console.WriteLine("The number {0} was not found.", myNumber);
        goto Finish;

    Found:
        Console.WriteLine("The number {0} is found.", myNumber);

    Finish:
        Console.WriteLine("End of search.");
    }
}
/*
Sample Input: 44

Sample Output
Enter the number to search for: 44
The number 44 is found.
End of search.
*/

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 5.3.3.10 Break, continue 및 goto 문

  • 8.9.3 goto 문

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 키워드

The goto Statement

점프문(C# 참조)

기타 리소스

C# 참조