if-else 문(C++)

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

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

  • 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:
ifconstexpropt17init-statement(opt17condition)if-branch
ifconstexpropt17init-statement(opt17condition)if-branchelseelse-branch

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

if-else 문

구조체를 if 제외한 모든 값을 가질 수 있는 문의 condition모든 형식에서 모든 부작용을 포함하여 평가됩니다. 실행되거나 , 또는 goto.를 포함하지 않는 한 if-branchelse-branch 컨트롤은 명령문에서 if 프로그램의 다음 문으로 breakcontinue전달됩니다.

문의 절 if...elseelse 해당 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); 하는 경우 문이 false이고 코드가 실행되지 않더라 if 도 포인터가 아니므로 오류가 return *tt 발생합니다.
  • 호출 ShowValue(pB); 하는 경우 문이 true이고 코드가 실행되지 않더라 if 도 포인터이기 때문에 t 오류가 return t 발생합니다.

함수 if constexpr 템플릿으로 전송된 인수의 형식과 일치하는 문만 컴파일되므로 이 문제를 해결합니다.

출력:

42
42

참고 항목

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