continue 문

continue 문 (continue statement)

루프를 돌다가 현재 반복을 중단하고 다음 반복으로 넘어가고 싶을 때가 있어요. continue 문이 바로 그 역할을 해요. 이 페이지에서 continue가 어디에서 어떤 식으로 동작하는지 살펴볼게요.

출처: cppreference

본문

구문 (Syntax)

attr (optional) continue ;
  • attr — (since C++11) 원하는 개수의 속성.

설명 (Explanation)

continue 문은 다음 문 중 하나에 둘러싸여 있어야 해요.

  • 반복 문(iteration statements): for, range-for, while, do-while
  • 확장 문(expansion statements): template for(since C++26)

반복 문에서 (For iteration statements)

continue 문을 실행할 때, 가장 안쪽에 있는 그런 둘러싸는 문이 반복 문이라면 제어 흐름은 반복 요소의 문(즉 루프 본문)의 끝으로 넘어가요.

while (/* ... */)
{
    /* executed statements */
    continue;
    /* skipped statements */
}

do
{
    /* executed statements */
    continue;
    /* skipped statements */
} while (/* ... */)

for (/* ... */)
{
    /* executed statements */
    continue;
    /* skipped statements */
}

확장 문에서 (For expansion statements)

continue 문을 실행할 때, 가장 안쪽에 있는 그런 둘러싸는 문이 확장 문이라면 제어 흐름은 확장 요소의 현재 확장 항목의 복합문 끝으로 넘어가요.

template for (/* ... */)
{
    if (/* current item is the Nth */)
        continue;
    /* statements only skipped for the Nth item */
}

(since C++26)

키워드 (Keywords)

continue

예제 (Example)

#include <iostream>

int main()
{
    for (int i = 0; i < 10; ++i)
    {
        if (i != 5)
            continue;
        std::cout << i << ' ';      // this statement is skipped each time i != 5
    }
    std::cout << '\n';
    
    for (int j = 0; 2 != j; ++j)
        for (int k = 0; k < 5; ++k) // only this loop is affected by continue
        {
            if (k == 3)
                continue;
            // this statement is skipped each time k == 3:
            std::cout << '(' << j << ',' << k << ") ";
        }
    std::cout << '\n';
}

출력:

5
(0,0) (0,1) (0,2) (0,4) (1,0) (1,1) (1,2) (1,4)

더 알아보기