if-else 語句 (C++)

if-else 語句會控制條件式分支。 只有在 評估為非零值 (或 true ) 時 condition ,才會執行 中的 if-branch 語句。 如果 的值 condition 不是零,則會執行下列語句,並略過選擇性 else 之後的 語句。 否則,會略過下列語句,如果有 else ,則會執行之後 else 的 語句。

condition 評估為非零的運算式包括:

  • true
  • 非 Null 指標,
  • 任何非零算術值,或
  • 類別類型,定義對算術、布林值或指標類型的明確轉換。 (如需轉換的相關資訊,請參閱 標準轉換。

語法

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
ifconstexpropt 17 init-statement( opt 17condition)if-branch
ifconstexpropt 17 init-statement( opt 17condition)if-branchelseelse-branch

17 從 C++17 開始,即可使用這個選擇性專案。

if-else 語句

在 語句的所有形式中 ifcondition 會評估結構以外的任何值,包括所有副作用。 除非執行 if-branchelse-branch 包含 、 continuegoto ,否則控制項會從 if 語句傳遞至程式中的下一個 break 語句。

語句 else 的 子句與沒有對應 else 語句之相同範圍中最接近的上 if 一個 if...else 語句相關聯。

範例

此範例程式碼示範使用中的數 if 個 語句,以及搭配 和 不使用 else

// 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-statement 的範圍內才需要變數時,請使用這個形式的 if-statement。 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

如果 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); 時收到錯誤 return *t ,因為 t 不是指標,即使 if 語句為 false 且永遠不會執行程式碼也一樣。
  • 如果您呼叫 ShowValue(pB); 時收到錯誤 return t ,因為 t 是指標,即使 if 語句為 true,而且永遠不會執行程式碼。

使用 if constexpr 可解決此問題,因為只會編譯符合傳送至函式範本之引數類型的語句。

輸出:

42
42

另請參閱

選取範圍陳述式
關鍵字
switch 語句 (C++)