C++17 If statement with initializer


C++17 has extended existing if statement’s syntax. Now it is possible to provide initial condition within if statement itself. This new syntax is called "if statement with initializer". This enhancement simplifies common code patterns and helps users keep scopes tight. Which in turn avoids variable leaking outside the scope.

Example

Let us suppose we want to check whether given number is even or odd. Before C++17 our code used to look like this −

 Live Demo

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

Output

When you compile and execute the above code it will generate output something like this −

1555814729 is an odd number

In the above example, we can see that variable "random_num" is leaked outside the if-else scope. We can easily avoid this with new "if statement with initializer" syntax.

Below is the syntax of "if statement with initializer" −

if (init; condition) {
   // Do stuff when Boolean condition is true
} else {
   // Do stuff when Boolean condition is false
}

Example

Now let us write same code using this new if statement with initializer −

 Live Demo

#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";
   }
   return 0;
}

In above example, scope of variable "random_num" is limited to if-else block. Hence this variable won't be accessible outside this block. Surprisingly it keeps variables scope tight without affecting actual output.

Output

When you compile and execute above code it will generate output something like this −

943513352 is an even number

NOTE − As we are generating random number each time output will vary for each run even on same machine.

Updated on: 26-Sep-2019

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements