Search⌘ K
AI Features

Init Statement for if and switch

Explore the use of init statements in C++17 with if and switch structures. Understand how defining variables within these statements limits their scope to the conditional blocks, preventing leakage and enhancing code clarity. This lesson helps you write more readable and maintainable conditional code using the latest C++17 features.

We'll cover the following...

C++17 provides new versions of the if and switch statements:

if (init; condition)

And

switch (init; condition)

In the init section you can specify a new variable, similarly to the init section in for loop. Then check the variable in the condition section. The variable is visible only in if/else scope.

To achieve a similar result, before C++17 you had to write:

C++
{
auto val = GetValue();
if (condition(val))
// on success
else
// on false...
}

Please notice that val has a separate scope, without that it ‘leaks’ to enclosing scope.

Now, in C++17, you can write:

C++
if (auto val = GetValue(); condition(val))
// on success
else
// on false...

Notice that val is visible only inside the if and else statements, so it doesn’t ‘leak.’

condition might be any boolean condition.

Here is an example:

C++ 17
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main() {
srand (time(NULL));
if (auto val = (rand() % 100); val > 50)
// on success
cout << val << " is greater than 50";
else
// on false...
cout << val << " is less than 50";
}

Why is this useful? We’ll discuss and example in the next lesson.