Local Variables In Control Flow Statements¶
if
Locals: Basis¶
#include <iostream>
unsigned foo()
{
return 42;
}
int main()
{
if (unsigned f = foo(); f%2==0)
std::cout << "foo returned " << f << " which is even\n";
else
std::cout << "foo returned " << f << " which is odd\n";
// std::cout << "foo returned " << f << '\n'; // <-- f only valid in if/else
return 0;
}
if
Locals: Use Case: std::map<>
Lookup¶
#include <map>
#include <iostream>
const std::map<int, const char*> int_words{
{ 42, "fourty-two" },
{ 7, "seven" },
};
int main()
{
if (auto found = int_words.find(42); found != int_words.end())
std::cout << found->second << '\n';
else
std::cout << "bummer\n";
return 0;
}
if
Locals: Use Case: Scoped Locking¶
#include <mutex>
#include <iostream>
std::mutex lock;
int shared_count = 0;
const char* shared_resource;
void shared_resource_alloc()
{
shared_resource = new const char[]{"Howdy"};
}
void shared_resource_free()
{
delete[] shared_resource;
}
int main()
{
if (std::scoped_lock _(lock); shared_count == 0) {
shared_resource_alloc();
++shared_count;
}
std::cout << shared_resource << '\n';
if (std::scoped_lock _(lock); shared_count == 1)
shared_resource_free();
return 0;
}
for
Locals: Good Old Times¶
Traditional for
loop has always had locals
#include <iostream>
int main()
{
for (int i=0; i<10; i++) // <-- for-local (since ages)
std::cout << i << std::endl;
return 0;
}
Range for
Locals: Only Logical ⟶ New In C++20¶
#include <iostream>
#include <array>
std::array numbers = {3, 1, 2, 4, 7, 100};
int main()
{
for (auto size=numbers.size(); int n: numbers) {
std::cout << n;
if (--size > 0)
std::cout << ',';
else
std::cout << '\n';
}
return 0;
}