In C++17, what is the scope of n in the statement if (int n = compute(); n > 0) { … } else { … }?
Correct answer C. Both the if branch and the else branch
C++17 added an init-statement to if and switch. A variable declared there is in scope throughout the whole if statement, including the condition, the if branch and any else branch, and it is destroyed when the statement ends. This keeps helper variables tightly scoped instead of leaking into the surrounding function, which a declaration before the if would do.
Answer checked How we write and check questions
Discussion