점프문 (Jump Statement)은 흐름을 끊고 프로그램의 실행 위치를 원하는 곳으로 단숨에 도약시킬 수 있다.
break현재 실행 중인 반복문이나 switch 문의 실행을 중단하고자 할 때 사용한다.
반복문이나 switch 문의 중단시키려는 지점에 break; 를 입력해두면 된다.
using System;
namespace Jump_Statement
{
class MainApp
{
static void Main(string[] args)
{
while (true)
{
Console.Write("계속할까요? (Y/N) : ");
string answer = Console.ReadLine();
if (answer == "N")
break;
}
}
}
}
계속할까요? (Y/N) : Y
계속할까요? (Y/N) : Y
계속할까요? (Y/N) : Y
계속할까요? (Y/N) : Y
계속할까요? (Y/N) : N
continue반복문을 멈추게 하는 break 문과 달리, continue 문은 반복문을 1 회 건너 뛰어 반복을 계속 수행하게 하는
기능을 한다.
다음과 같이 continue 문이 반복문 안에 사용되면, i 가 3 인 경우 현재 실행 중인 반복을 건너뛰고 다음
반복으로 넘어간다.
for (int i = 0; i < 5; ++i)
{
if (i == 3)
continue;
Console.WriteLine(i);
}
using System;
namespace Jump_Statement
{
class MainApp
{
static void Main(string[] args)
{
for (int i = 0; i < 10; ++i)
{
if (0 == i % 2)
continue;
Console.WriteLine($"{i} : 홀수");
}
}
}
}
1 : 홀수
3 : 홀수
5 : 홀수
7 : 홀수
9 : 홀수
gotogoto 문은 레이블이 가리키는 곳으로 바로 뛰어 넘어간다.
여기서 레이블(Label)이란 변수하고는 조금 다른데, 코드안의 위치를 나타내는 표시판 같은 존재이다.
using System;
namespace Jump_Statement
{
class MainApp
{
static void Main(string[] args)
{
Console.Write("종료 조건(숫자)를 입력하세요. : ");
string input = Console.ReadLine();
int input_number = Convert.ToInt32(input);
int exit_number = 0;
for (int i = 0; i < 10; ++i)
{
// 조건이 참이면 EXIT_FOR 로 점프
if (exit_number++ == input_number)
goto EXIT_FOR;
Console.WriteLine(exit_number);
}
// EXIT_PROGRAM 로 점프
goto EXIT_PROGRAM;
EXIT_FOR:
Console.WriteLine("Exit nested for...");
EXIT_PROGRAM:
Console.WriteLine("Exit program...");
}
}
}
종료 조건(숫자)를 입력하세요. : 5
1
2
3
4
5
Exit nested for...
Exit program...
종료 조건(숫자)를 입력하세요. : 12
1
2
3
4
5
6
7
8
9
10
Exit program...
상당수의 프로그래머는 goto 문을 별로 좋아하지 않는다.
goto 문이 코드의 이곳저곳으로 이동하면서 흐름을 자주 끊어 코드를 읽기 어렵게 만들기 때문이다.