Initialize Variables within if and switch Statements
Learn to initialize variables within if and switch statements.
We'll cover the following...
Beginning with C++17, if
and switch
now have initialization syntax, much like the for
loop has had since C99. This allows we to limit the scope of variables used within the condition.
How to do it
You may be accustomed to code like this:
Press + to interact
#include <iostream>#include <string>using std::cout;using std::string;using std::size_t;int main() {const string artist{ "Jimi Hendrix" };size_t pos{ artist.find("Jimi") };if(pos != string::npos) {cout << "found\n";} else {cout << "not found\n";}return 0;}
This leaves the variable pos
exposed outside the scope of the conditional statement, where it needs to be managed, or it can collide with other attempts to use the same symbol.
Now we can put the initialization expression inside the if
...