Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++17 If Statement with Initializer (คำสั่ง If พร้อมตัวเริ่มต้น)


C++17 ขยายไวยากรณ์ if statement ให้สามารถประกาศตัวแปรเริ่มต้น (initializer) ภายใน if เองได้ เรียกว่า "if statement with initializer" ช่วยลดขอบเขตตัวแปร (scope) ป้องกันการรั่วไหลของตัวแปรนอกบล็อก

ตัวอย่างก่อน C++17

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    srand(time(NULL));
    int random_num = rand();
    if (random_num % 2 == 0) {
        cout << random_num << " is an even number\n";
    } else {
        cout << random_num << " is an odd number\n";
    }
    return 0;
}

ตัวแปร random_num รั่วไหลออกนอก if-else

ไวยากรณ์ใหม่ C++17

if (init; condition) {
    // ทำเมื่อ condition เป็น true
} else {
    // ทำเมื่อ condition เป็น false
}

ตัวอย่าง C++17

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    srand(time(NULL));
    // C++17 if statement with initializer
    if (int random_num = rand(); random_num % 2 == 0) {
        cout << random_num << " is an even number\n";
    } else {
        cout << random_num << " is an odd number\n";
    }
    // random_num ไม่สามารถเข้าถึงได้ที่นี่
    return 0;
}

ตัวแปร random_num อยู่ในขอบเขต if-else เท่านั้น

ผลลัพธ์

943513352 is an even number

หมายเหตุ — เนื่องจากใช้สุ่มตัวเลข ผลลัพธ์จะต่างกันทุกครั้ง