ในหลายกรณี เราจำเป็นต้องตรวจสอบค่าของบางสิ่งที่ส่งคืนโดยฟังก์ชันและดำเนินการตามเงื่อนไขตามค่านี้ ดังนั้นรหัสของเราจะได้รับด้านล่าง -
// Some method or function
return_type foo(Params)
// Call function with Params and
// store return in var1
auto var1 = foo(Params);
if (var1 == /* some value */) {
//Perform Something
} else {
//Perform Something else
} เพียงทำตามรูปแบบทั่วไปในบล็อกเงื่อนไข if-else ทั้งหมด ประการแรก มีคำสั่งเริ่มต้นซึ่งเป็นทางเลือกซึ่งตั้งค่าตัวแปร ตามด้วยบล็อก if-else ดังนั้นบล็อก if-else ทั่วไปจะได้รับดังนี้ -
init-statement
if (condition) {
// Perform or Do Something
} else {
// Perform or Do Something else
} ใน C++17 คำสั่ง init จะแสดงหรือเรียกว่า initializer และเราสามารถเก็บไว้ในบล็อก if-else ได้โดยตรงในลักษณะดังต่อไปนี้
if (init-statement; condition) {
// Perform Something
} else {
// Perform Something else
} ขอบเขตของตัวแปรแบบมีเงื่อนไขถูกจำกัดหรือจำกัดเฉพาะบล็อก if-else ปัจจุบัน นอกจากนี้ยังอนุญาตให้เราใช้ตัวระบุที่มีชื่อเดิมซ้ำในบล็อกแบบมีเงื่อนไขอื่น
if (auto var1 = foo(); condition) {
...
}
else{
...
}
// Another if-else block
if (auto var1 = bar(); condition) {
....
}
else {
....
} ในกรณีที่คล้ายกัน บล็อกเคสสวิตช์ได้รับการแก้ไขหรืออัปเดตแล้ว ตอนนี้เราสามารถเก็บนิพจน์เริ่มต้นไว้ในวงเล็บสวิตช์ได้แล้ว
หลังจากคำสั่งเริ่มต้น เราจำเป็นต้องระบุว่าตัวแปรใดที่กำลังดำเนินการตรวจสอบกรณีต่างๆ
switch (initial-statement; variable) {
....
// cases
} โปรแกรมที่สมบูรณ์
// Program to explain or demonstrate init if-else
// feature introduced in C++17
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
// Fix or set up rand function to be implemented
// later in program
srand(time(NULL));
// Before C++17
int I = 2;
if ( I % 2 == 0)
cout << I << " is even number" << endl;
// After C++17
// if(init-statement; condition)
if (int I = 4; I % 2 == 0 )
cout<< I << " is even number" << endl;
// Switch statement
// switch(init;variable)
switch (int I = rand() % 100; I) {
default:
cout<< "I = " << I << endl; break;
}
}