Search⌘ K

Using if In A Search Statement

Explore how C++17 enhances if statements by allowing variable initialization inside the condition. Understand how this feature helps streamline search operations in strings and supports structured bindings for clearer code. Learn to balance readability when using this new syntax.

We'll cover the following...

We learned that C++17 allows us to specify a new variable which can be used in the condition. This variable is inside the if condition scope:

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

Let’s see if this is useful. Say you want to search for a few things in a string:

Method 1
Method 2
Error
#include <iostream>
using namespace std;
int main() {
// your code goes here
const std::string myString = "My Hello World Wow";
const auto pos = myString.find("Hello");
if (pos != std::string::npos)
std::cout << pos << " Hello\n";
const auto pos2 = myString.find("World");
if (pos2 != std::string::npos)
std::cout << pos2 << " World\n";
}

As you can see, you have to use different names for pos or enclose it with a separate scope, otherwise the code will fail as it does ...