Home Item 18 - if 語句中的初始化 (中文)
Post
Cancel

Item 18 - if 語句中的初始化 (中文)

if 語句中的初始化

功能如同標題,這篇比較簡單,C++17 引入了一項新特性,即在 if 語句中進行初始化。 這使得我們可以在 if 語句中同時聲明並初始化變量,並將其限制在 if 語句的作用域內。 這樣可以使代碼更加簡潔,並避免了變量泄露到更大的作用域。

語法 C++17 中,if 語句的語法可以寫成如下形式:

1
2
3
4
5
6
if (init_statement; condition)
{
    // code block
}

來看以下例子就更清楚了

開檔時的檢查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>

int main() {
    if (std::ifstream file{"example.txt"}; file.is_open()) {
        std::cout << "File opened successfully." << '\n';
    } else {
        std::cout << "Failed to open the file." << '\n';
    }

    return 0;
}


指標檢查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main() {
    int x = 10;
    int* p = &x;

    if (int* ptr = p; ptr) {
        std::cout << "Pointer is valid and points to: " << *ptr << '\n';
    } else {
        std::cout << "Pointer is null." << '\n';
    }

    return 0;
}

數學計算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main() {
    int a = 5;
    int b = 10;
    a++;

    if (int sum = a + b; sum > 10) {
        std::cout << "Sum is greater than 10: " << sum << '\n';
    } else {
        std::cout << "Sum is 10 or less: " << sum << '\n';
    }

    return 0;
}

看一下中斷點及區域變數 以下共有3個中斷點,

Desktop View

區域變數此時還沒有 sum

Desktop View

Desktop View

區域變數 sum 出現了

Desktop View

Desktop View

離開 if scope sum 消失了

Desktop View

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍