다음을 통해 공유


if-else 문(C++)

if-else 문은 조건부 분기를 제어합니다. if-branch의 문은 condition이 0이 아닌 값(또는 true)으로 계산되는 경우에만 실행됩니다. condition의 값이 0이 아닌 경우 다음 문이 실행되고 선택적 else 뒤의 문은 건너뜁니다. 그렇지 않으면 다음 문을 건너뛰고, else가 있으면 else 다음 문이 실행됩니다.

0이 아닌 것으로 계산되는 condition 식은 다음과 같습니다.

  • true
  • null이 아닌 포인터,
  • 0이 아닌 산술 값, 또는
  • 산술, 부울 또는 포인터 형식으로의 명확한 변환을 정의하는 클래스 형식입니다. (변환에 대한 자세한 내용은 표준 변환을 참조하세요.)

구문

init-statement:
expression-statement
simple-declaration

condition:
expression
attribute-specifier-seqoptdecl-specifier-seqdeclaratorbrace-or-equal-initializer

statement:
expression-statement
compound-statement

expression-statement:
expressionopt;

compound-statement:
{statement-seqopt}

statement-seq:
statement
statement-seq statement

if-branch:
statement

else-branch:
statement

selection-statement:
ifconstexpropt17(init-statementopt17condition)if-branch
ifconstexpropt17(init-statementopt17condition)if-branchelseelse-branch

17 이 선택 요소는 C++17부터 사용할 수 있습니다.

if-else 문

모든 형태의 if 문의 경우 구조를 제외한 모든 값을 가질 수 있는 condition이 모든 파생 작업을 포함하여 계산됩니다. 실행된 if-branch 또는 else-branchbreak, continue 또는 goto가 포함되지 않는 한, if 문에서 프로그램의 다음 문으로 제어가 전달됩니다.

if...else 문의 else 절은 해당 else 문이 없는 동일한 범위에서 가장 가까운 이전 if 문과 연결되어 있습니다.

예시

이 샘플 코드는 else 유무에 관계없이 사용 중인 여러 if 문을 보여 줍니다.

// if_else_statement.cpp
#include <iostream>

using namespace std;

int main()
{
    int x = 10;

    if (x < 11)
    {
        cout << "x < 11 is true!\n";  // executed
    }
    else
    {
        cout << "x < 11 is false!\n"; // not executed
    }

    // no else statement
    bool flag = false;
    if (flag == true)
    {
        x = 100; // not executed
    }

    int *p = new int(25);
    if (p)
    {
        cout << *p << "\n"; // outputs 25
    }
    else
    {
        cout << "p is null!\n"; // executed if memory allocation fails
    }
}

출력

x < 11 is true!
25

이니셜라이저가 있는 if 문

C++17부터 if 문에는 명명된 변수를 선언하고 초기화하는 init-statement 식이 포함될 수도 있습니다. if 문 범위 내에서만 변수가 필요한 경우 이 형식의 if 문을 사용합니다. Microsoft 전용: 이 양식은 Visual Studio 2017 버전 15.3부터 사용할 수 있으며 최소한 /std:c++17 컴파일러 옵션이 필요합니다.

// Compile with /std:c++17

#include <iostream>
#include <mutex>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

map<int, string> m{ {1, "one"}, {2, "two"}, {10,"ten"} };
mutex mx;
bool shared_flag = true; // guarded by mx
int getValue() { return 42; }

int main()
{
    if (auto it = m.find(10); it != m.end())
    {
        cout << it->second << "\n";
    }

    if (int x = getValue(); x == 42)
    {
        cout << "x is 42\n";
    }

    if (lock_guard<mutex> lock(mx); shared_flag)
    {
        cout << "setting shared_flag to false\n";
        shared_flag = false;
    }

    string s{ "if" };
    if (auto keywords = { "if", "for", "while" }; any_of(keywords.begin(), keywords.end(), [&s](const char* kw) { return s == kw; }))
    {
        cout << "Error! Token must not be a keyword\n";
    }
}

출력:

ten
x is 42
setting shared_flag to false
Error! Token must not be a keyword

if constexpr 문

C++17부터 함수 템플릿에서 if constexpr 문을 사용하여 여러 함수 오버로드에 의존하지 않고도 컴파일 시간 분기 결정을 내릴 수 있습니다. Microsoft 전용: 이 양식은 Visual Studio 2017 버전 15.3부터 사용할 수 있으며 최소한 /std:c++17 컴파일러 옵션이 필요합니다.

예시

이 예에서는 전송된 형식에 따라 템플릿을 조건부로 컴파일하는 방법을 보여 줍니다.

// Compile with /std:c++17
#include <iostream>

template<typename T>
auto Show(T t)
{
    //if (std::is_pointer_v<T>) // Show(a) results in compiler error for return *t. Show(b) results in compiler error for return t.
    if constexpr (std::is_pointer_v<T>) // This statement goes away for Show(a)
    {
        return *t;
    }
    else
    {
        return t;
    }
}

int main()
{
    int a = 42;
    int* pB = &a;

    std::cout << Show(a) << "\n"; // prints "42"
    std::cout << Show(pB) << "\n"; // prints "42"
}

if constexpr 문은 컴파일 시간에 계산되며 컴파일러는 함수 템플릿에 전송된 인수 형식과 일치하는 if 분기에 대한 코드만 생성합니다. if constexpr 문을 주석으로 처리하고 if 문의 주석 처리를 제거하면 컴파일러는 두 분기 모두에 대한 코드를 생성합니다. 즉, 오류가 발생합니다.

  • ShowValue(a);를 호출하면 if 문이 false이고 코드가 실행되지 않더라도 t가 포인터가 아니기 때문에 return *t에서 오류가 발생합니다.
  • ShowValue(pB);를 호출하면 if 문이 true이고 코드가 실행되지 않더라도 t가 포인터이기 때문에 return t에서 오류가 발생합니다.

함수 템플릿에 전송된 인수 형식과 일치하는 문만 컴파일되기 때문에 if constexpr를 사용하면 이 문제가 해결됩니다.

출력

42
42

참고 항목

선택 문
키워드
switch Statement (C++)