Else and Switch Statements with initializers in C++17

C++Server Side ProgrammingProgramming

In many cases, we need to verify the value of something returned by a function and perform conditional operations based on this value. So our code is given below −

// 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
}

Just follow the general format in all conditional if-else blocks. Firstly there is exist an optional initial statement which sets up the variable, followed by the if-else block. So the general if-else block is given as follows −

init-statement
if (condition) {
   // Perform or Do Something
} else {
   // Perform or Do Something else
}

In C++17 the init statement is denoted or called an initializer, and we can directly keep it into the if-else block as in following manner

if (init-statement; condition) {
   // Perform Something
} else {
   // Perform Something else
}

The scope of the conditioned variable gets confined or limited to the current if-else block. This also permits us to reuse the same named identifier in another conditional block.

if (auto var1 = foo(); condition) {
   ...
}
else{
   ...
}
// Another if-else block
if (auto var1 = bar(); condition) {
   ....
}
else {
....
}

In similar case the switch case block has been modified or updated. We can now keep an initial expression inside the switch parenthesis.

After the initial statement we require to specify which variable is being implemented to check the cases

switch (initial-statement; variable) {
   ....
   // cases
}

A complete program

// 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;
   }
}

raja
Published on 29-Jan-2020 11:52:23
Advertisements