To restrict the scope of visibility for a variable which is needed only within an if-block, you can define the variable directly within the if statement. After the if-block the defined variable is unknown.
Principle:
if (init; condition)
Concrete example:
int GetNumFromSomeWhere();
...
// within some function
if (int i = 5; i < 2)
{
std::cout << "i=" << i << std::endl;
}
else if (auto j = GetNumFromSomeWhere(); j < 0)
{
// here both i and j are existing
std::cout << "i=" << i << " j=" << j << std::endl;
}
else
{
// here also both i and j are existing
std::cout << "i=" << i << " j=" << j << std::endl;
}
// here both i and j are NOT existing
- use of “auto” within intializer list is possible
- variable declarations are available to all nested if-else sub blocks
Use of structured binding is also possible:
std::tuple<double, double, double> GetSomeCoords()
...
// within some function use structured binding
if (auto [x, y, z] = GetSomeCoords(); (x > 0.05) && (y < 2.2))
{
std::cout << "coord=" << x << "/" << y << "/" << z << "/" << std::endl;
}
Restriction: You cannot initialize 2 or more variables of different types within a single if-statement (except using structured binding)
Remark: Ugly initialization of multiple values of the same type is possible:
int i=0, j=5;
The same rules for initialization apply also to switch and for statements:
switch (init; var)
for (auto vec = std::vector{1,2,3}; auto v : vec) {/*iterate over vec*/}