Daily bit(e) of C++ | Init statements

Šimon Tóth
May 6, 2023

Daily bit(e) of C++ #125, The C++17 (if, switch) and C++20 (range-for) init statements.

Init statements enable fully encapsulated if, switch (C++17) and range-for loop (C++20) statements by adding an additional init section that can be used to create variables with a lifetime matching the statement block.

#include <string>
#include <optional>

std::optional<int> some_call() {
return 10;
}

int other_call() { return 10; }


// C++17
if (auto result = some_call(); result.has_value()) {
int v = *result;
}

// C++17
switch (auto val = other_call(); val) {
case 1: // further process val
break;
case 2: // further process val
break;
default:
;
}

// C++20 / Enables iteration over temporary ranges.
for(std::string v = std::to_string(42); auto c : v) {
// v is a valid range that can be safely iterated over
}

Open the example in Compiler Explorer.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Šimon Tóth
Šimon Tóth

Written by Šimon Tóth

20 years worth of Software Engineering experience distilled into easily digestible articles.

No responses yet

Write a response