According to the standard, what is the difference in behavior between declaring variables in control structures versus declaring variables elsewhere? I can’t seem to find any mention of it.
If what I’m referring to isn’t clear, here’s an example:
if (std::shared_ptr<Object> obj = objWeakPtr.lock())
As you can see, I’m declaring and initializing a local variable, obj, in the if block.
Also, is there any technical reason as to why this syntax isn’t given any special behavior when used in place of a conditional? For example, adding an additional set of brackets results in a compiler error; this also prevents the variable from being chained with other conditions.
// Extra brackets, won't compile.
if ((std::shared_ptr<Object> obj = objWeakPtr.lock()))
// If the above were valid, something like this could be desirable.
if ((std::shared_ptr<Object> obj = objWeakPtr.lock()) && obj->someCondition())
Declarations inside control structure introductions are no different that declarations elsewhere. That’s why you can’t find any differences.
6.4/3 does describe some specific semantics for this, but there are no surprises:
An
ifcondition can contain either a declarative statement or an expression. No expression may contain a declarative statement, so you can’t mix them either.It all just follows from the grammar productions.