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-seq선택decl-specifier-seqdeclaratorbrace-or-equal-initializer

statement:
expression-statement
compound-statement

expression-statement:
expression선택;

compound-statement:
{statement-seq선택}

statement-seq:
statement
statement-seq statement

if-branch:
statement

else-branch:
statement

selection-statement:
ifconstexpropt 17(init-statementopt17condition)if-branch
ifconstexpropt 17(init-statementopt17condition)if-branchelseelse-branch

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

if-else 문

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

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

이 샘플 코드는 사용 중인 몇 가지 if 문을 보여 줍니다. 둘 다 사용 중이고 없는 else문은 모두 입니다.

// if_else_statement.cpp
#include <iostream>

using namespace std;

class C
{
    public:
    void do_something(){}
};
void init(C){}
bool is_true() { return true; }
int x = 10;

int main()
{
    if (is_true())
    {
        cout << "b is true!\n";  // executed
    }
    else
    {
        cout << "b is false!\n";
    }

    // no else statement
    if (x == 10)
    {
        x = 0;
    }

    C* c;
    init(c);
    if (c)
    {
        c->do_something();
    }
    else
    {
        cout << "c is null!\n";
    }
}

이니셜라이저가 있는 if 문

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

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

using namespace std;

map<int, string> m;
mutex mx;
bool shared_flag; // guarded by mx
void unsafe_operation() {}

int main()
{

    if (auto it = m.find(10); it != m.end())
    {
        cout << it->second;
        return 0;
    }

    if (char buf[10]; fgets(buf, 10, stdin))
    {
        m[0] += buf;
    }

    if (lock_guard<mutex> lock(mx); shared_flag)
    {
        unsafe_operation();
        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";
    }
}

if constexpr 문

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

이 예제에서는 매개 변수 압축 해제를 처리하는 단일 함수를 작성하는 방법을 보여 줍니다. 매개 변수가 0인 오버로드는 필요하지 않습니다.

template <class T, class... Rest>
void f(T&& t, Rest&&... r)
{
    // handle t
    do_something(t);

    // handle r conditionally
    if constexpr (sizeof...(r))
    {
        f(r...);
    }
    else
    {
        g(r...);
    }
}

추가 정보

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