Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

C++17 If statement with initializer (If có khởi tạo)


C++17 mở rộng cú pháp if cho phép khai báo biến ngay trong điều kiện:

if (init; condition) { ... } else { ... }

Biến init chỉ tồn tại trong scope của if-else, tránh rò rỉ biến (variable leaking).

Ví dụ so sánh

Trước C++17

int random_num = rand(); // Bien le o ngoai scope
if (random_num % 2 == 0) ...
else ...
// random_num van con ton tai o day

C++17 If with initializer

if (int random_num = rand(); random_num % 2 == 0) {
    cout << random_num << " la chan\n";
} else {
    cout << random_num << " la le\n";
}
// random_num KHONG con ton tai o day

Ứng dụng thực tế

  • Map lookup: if (auto it = m.find(key); it != m.end()) { use(it->second); }
  • Lock guard: if (auto lock = mutex.lock(); condition) { ... }
  • File handle: if (FILE* f = fopen(...); f) { ... }

Chương trình demo

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

int main() {
    srand(time(nullptr));
    
    // Demo 1: Random even/odd
    if (int n = rand(); n % 2 == 0)
        cout << n << " la chan\n";
    else
        cout << n << " la le\n";
    // n khong the truy cap o day
    
    // Demo 2: Map search
    unordered_map mp = {{"apple",5}, {"banana",3}};
    if (auto it = mp.find("apple"); it != mp.end())
        cout << "Tim thay: " << it->first << " = " << it->second << "\n";
    else
        cout << "Khong tim thay\n";
    
    return 0;
}

Kết quả

1804289383 la le
Tim thay: apple = 5