The Essentials of C++, David hunter

Chapter 2. Control Structures

2.1 Selectional Structures 선택 구조

2.1.1 if

  • The general form of the if statement is shown below.

  • if 문의 일반적인 형식은 아래와 같이 표시됩니다.

if (expression)
{
    statement;
    statement;
    ...
};
else
{
    statement;
    statement;
    ...
};
  • The expression to be tested must be enclosed in parentheses. The else portion is optional. Grouping symbols in the if and the else are not required if only one statement is to be selected.

  • 테스트할 표현식은 괄호로 묶어야 합니다. else 부분은 선택 사항입니다. if와 else에서 그룹화 기호는 하나의 문장만 선택해야 할 경우 필요하지 않습니다.

  • Because C++ has no boolean data type, any legitimate C++ expression, including assignments and I/O, may be the subject of an if statement. Whatever expression is specified is evaluated and, if non-zero, the “true” branch of the if is executed. If the expression results in a value of zero, the “false” branch is executed.

  • C++에는 불리언 데이터 유형이 없으므로 할당 및 I/O를 포함한 모든 합법적인 C++ 표현식은 if 문의 주제가 될 수 있습니다. 지정된 표현식은 평가되고, 그 값이 0이 아닌 경우 if의 “true” 브랜치가 실행됩니다. 표현식의 결과가 0인 경우 “false” 브랜치가 실행됩니다.

  • This open-ended nature of the if is a frequent cause of error for beginning C++ programmers, as shown in the examples below.

  • if의 이러한 개방적인 특성은 초보 C++ 프로그래머에게 오류의 일반적인 원인이 되며, 아래의 예시에서 볼 수 있습니다.

if (a = 10) // SERIOUS BUG!
{
    ...
};
if ((a > b) & (c < d)) // SERIOUS BUG!
{
    ...
};
if (! a > b) // SERIOUS BUG!
{
    ...
};
  • In the first example, the programmer has intended to test if a is equal to 10. Instead, the code assigns 10 to a then excutes the body of the if. The if body will always be executed because 10 is non-zero. In the second example, a logical AND was intended but instead a bitwise AND is performed on the results of the expression (a>b) and (c<d). Finally, in the third example, since the NOT operator has a higher precedence than the greater than operator, the expression first performs logical NOT on a, then compares the result to b.

  • 첫 번째 예제에서 프로그래머는 a가 10과 같은지를 테스트하려고 의도했습니다. 그러나 코드는 a에 10을 할당한 다음 if의 본문을 실행합니다. 10은 0이 아니므로 if 본문은 항상 실행됩니다. 두 번째 예제에서 논리 AND가 의도되었지만 대신 표현식 (a>b)(c<d)의 결과에 비트 AND가 수행됩니다. 마지막으로 세 번째 예제에서 NOT 연산자는 더 큰 우선순위를 가지므로 먼저 a에 대한 논리 NOT을 수행한 다음 결과를 b와 비교합니다.

  • 수정된 코드

if (a == 10) // 수정: 등호 연산자 (==)를 사용하여 비교
{
    // ...
}

if ((a > b) && (c < d)) // 수정: 논리 AND 연산자 (&&)를 사용
{
    // ...
}

if (!(a > b)) // 수정: 논리 NOT 연산자 (!)를 적용
{
    // ...
}

2.1.2 Conditional Assignment 조건부 할당

  • C++ allows statements of the form if (test) var = val1 else var = val2 to be written using the notation var = test ? val1 : val2. For example, the statement is equivalent to the following:

  • C++에서는 if (test) var = val1 else var = val2와 같은 형식의 문을 var = test ? val1 : val2 표기법을 사용하여 작성할 수 있습니다. 예시는 다음과 같습니다:

a = (n > 10) ? b : c;
if (n > 10)
    a = b;
else
    a = c;

2.1.3 switch

  • The switch statement is used to select statements based on the value of a variable. In the example provided below, the first group of statements is executed if expression is equal to *value1, the second group if expression is either value2 or value3, and the third group is selected if none of the other cases apply. The break statement transfers control out of the switch.

  • switch 문은 변수의 값에 따라 문장을 선택하는 데 사용됩니다. 아래 제공된 예제에서, 첫 번째 그룹의 문장은 expression이 value1과 같으면 실행되고, 두 번째 그룹은 expression이 value2 또는 value3인 경우 실행되며, 나머지 경우에는 세 번째 그룹이 선택됩니다. break 문은 switch에서 제어를 빠져나가게 됩니다.

switch (expression)
{
    case value1:
        statement;
        statement;
        // ...
        break;
    case value2:
    case value3:
        statement;
        statement;
        // ...
        break;
    default:
        statement;
        statement;
        // ...
        break;
}
  • When a switch statement is encountered, the specified expression is evaluated and an appropriate case selected. Execution begins at that point and continues downward until either a break is executed or the end of the switch is reached.

  • switch 문을 만나면 지정된 표현식이 평가되고 적절한 case가 선택됩니다. 실행은 해당 지점에서 시작하여 break가 실행되거나 switch의 끝에 도달할 때까지 아래로 계속됩니다.

Looping Constructs 반복 구조

2.2.1 while

  • The two logic controlled loops in C++ are illustrated below.

  • C++에서 사용되는 두 가지 논리 제어 반복문은 아래에 설명된 대로 나타낼 수 있습니다.

while (expression)
{
    statement;
    statement;
    // ...
}
do
{
    statement;
    statement;
    // ...
} while (expression);

추가 설명

  • while과 do while의 차이점
    • 루프의 조건을 검사하는 시점
    • while 루프는 루프의 조건을 먼저 검사합니다. 따라서 조건이 거짓인 경우 루프 내의 코드는 한 번도 실행되지 않을 수 있습니다.
    • do-while 루프는 루프 내의 코드를 먼저 한 번 실행한 다음, 조건을 검사합니다. 따라서 조건이 거짓이라도 루프 내의 코드는 최소한 한 번 실행됩니다.

2.2.2 for

  • The other looping construct provided by C++ is the for loop.

  • C++에서 제공하는 다른 반복 구조는 “for 루프”입니다.

for (initial expression; while test; increment)
{
    statement;
    statement;
    // ...
}
  • The initial expression is evaluated once upon entering the loop. The loop continues execution as long as the while test is true (non-zero). After each loop iteration (essentially, as the last statement of the loop body) the increment is performed. A standard count loop that iterates from 1 to 10 can therefore be implemented as:

  • 초기 표현식은 루프에 진입할 때 한 번 평가됩니다. 루프는 while 테스트가 true(0이 아닌)인 동안 계속 실행됩니다. 각 루프 반복에서 (본질적으로 루프 본문의 마지막 문장으로) 증가가 수행됩니다. 따라서 1부터 10까지 반복하는 표준 카운트 루프는 다음과 같이 구현할 수 있습니다:

for (int i = 1; i <= 10; ++i)
{
    // Do something
}
  • Since any legitimate C++ expression may be used in any of the three position of the for statement, however, this construct is considerably more general than that provided by most other languages.

  • 그러나 C++에서는 어떤 유효한 C++ 표현식이든 for 문의 세 위치 중 어느 곳에도 사용할 수 있으므로, 이 구조는 대부분의 다른 언어에서 제공하는 것보다 훨씬 더 일반적입니다.

2.2.3 break and continue

  • The break statement may be used to terminate a loop at any point. It transfers control to the first statement after the loop. The continue statement causes the loop to skip to its next iteration, essentially transferring control to the while, do or for statement.

  • break 문은 루프를 어떤 지점에서든 종료하는 데 사용될 수 있습니다. 이 문은 루프 다음의 첫 번째 문장으로 제어를 전달합니다. continue 문은 루프를 다음 반복으로 건너뛰도록 하며, 본질적으로 while, do, 또는 for 문으로 제어를 전달합니다.