It just so happened that I watched several C++ talks that mention upcoming feature of C++17 called "If statement with initializer" all in a relatively short time frame. Unfortunately, there was another common trait among all of these presentations, which is the topic of this post.
The feature
The feature itself is described in this paper and looks something like this:
if (type variable = function(); variable.check()) {
// ...
}
The code is almost equivalent to the following snippet with the exception of name scoping:
{
type variable = function();
if (variable.check()) {
// ...
}
}
Nothing special, it's just syntactic sugar.
The feature continued
After showing example of the new syntax, all presenters then went to demonstrate the following way of testing value of an optional (a type that either holds a value or is empty):
if (auto opt = getOptional(); opt) {
// ...
}
Looks almost ideal, right? It would be even better, if one could write the same code like this instead:
if (auto opt = getOptional()) {
// ...
}
But this won't be added in C++17. It won't be added in C++20. Or in any other future standard of C++, ever...
It won't make it not because it's bad, but because it's already there! And it wasn't introduced in C++14, C++11 or even C++03, it's literally there since the very first C++98 standard.
The surprise
It's not a big deal that speakers themselves didn't know about this old syntax, it's that they weren't corrected by anyone in the audience that surprises me. Especially since this happened on various conferences some of which praise themselves for being "the best" and "full of experts" (even though the same has probably been said at least once about every other conference).
It's just weird that they weren't aware of this useful syntax for so many years (I assume they would correct the speaker otherwise, like with other issues on slides). I was under impression that it's something that's relatively popular, but looks like I was wrong.
Also, since they were experimenting with the new feature, they could just try dropping the check part to see what happens.
Extra: the inconsistency
This proposal basically extends previously available syntax for for
, while
,
if
and switch
. The inconsistency is that only if
and switch
were
extended. It's probably less useful and somewhat problematic to extend for
,
but I don't see why while
was left out.
Some more examples, just to make sure everybody understands what was available
before (I remember being misunderstood at least about for
):
for (std::size_t i = 0U; auto opt = getOptionalElement(i); ++i) {
// use `opt` here
}
while (auto data = getData()) {
// process `data`
}
switch (char c = readChar()) {
// ...
default:
// use `c` here
break;
}
Instead of conclusion
If you didn't know this about C++98 before, don't think that you know all of C++98 now.