Practice mode C++

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

Explanation

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.